Как вернуть все элементы массива вместо одного элемента массива, используя WCF - PullRequest
0 голосов
/ 26 ноября 2018

Я создаю программу лотереи с использованием WCF, JSON и Windows Forms.

По сути, цель состоит в том, что когда пользователь нажимает на форме кнопки рисования ирландского лото или лото, 6 уникальных случайных чисел генерируются с использованием сервисов wcf, которые возвращаются и печатаются на каждой этикетке в форме.Минимальное значение массива - 1, максимальное - значения json 29 и 59 для розыгрыша ирландцев и лото соответственно.

Редактировать *

Вот краткое изложение назначения.Я не уверен, что это значит, используя Json для отправки данных туда и обратно.

  1. Вспомните последние WCF-сервисы и задачи JSON, которые вы создали в качестве отправной точки.

  2. Создайте приложение служб WCF так же, как вы это делали для этого.

  3. Добавьте метод для создания случайного числа от 1 до значенияВы будете отправлены.

  4. Создайте форму, которая позволит пользователю выбрать либо Лото, либо Ирландское Лото.

  5. Отправитьнеобходимое количество шаров для сервисов и получите набор случайных чисел.Отобразите их в форме.(Оба розыгрыша имеют различное количество номеров на выбор)

  6. Ваша форма лотереи должна использовать Услуги WCF, а не генерировать случайные числа непосредственно в форме.Используйте JSON для отправки данных туда и обратно.

  7. Протестируйте свое приложение.

LottoService.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;

namespace WcfLottoServiceApp
{

public class LottoService : ILottoService
{

    public int GenerateLottoDrawNums()
    {
        //Create a new instance of JObject to parse the value from JSON file and use that as the max value for the array
        JObject myJsonFile = JObject.Parse(File.ReadAllText(@"C:\Users\davie\Documents\UniWork\Advanced Programing\Lab3LottoJSONProgram\WcfLottoService\WcfLottoServiceApp\Lotto.Json"));

        //set min/max value of array to 1 and the json file value which is 59;
        int min = 1;
        int max = (int)myJsonFile["LottoDraw"];

        //declare and initilize an array with 6 values
        int[] randomNums = new int[6];

        //create new instance of Random 
        Random rand = new Random();

        //i starts at 0, keep looping whilst i is less than the lengh of the array which is 6
        for (int i = 0; i < randomNums.Length; i++)
        {
            //values are initially stored in tempNum to be checked against the current values in the array
            int tempNum = rand.Next(min, max); 

            // IsDup is true, tempNum is the temporary 7th value in the array. ie. 
            //the array only stores 6 values but there is a 7th tempary number incase any of the initial 6 
            //values are the same. The 7th number will keep looping until it is unique and add to the array so there is 6 unique values. 
            while (IsDuplicate(tempNum, randomNums))
            {
                tempNum = rand.Next(7);
            }
            randomNums[i] = tempNum;



        }



        PrintTheArray(randomNums);
        return randomNums[0];

    }


    public int GenerateIrishLottoNums()
    {
        //Create a new insatnce of JObject to parse the value from JSON file and use that as the max value for the array
        JObject myJsonFile = JObject.Parse(File.ReadAllText(@"C:\Users\davie\Documents\UniWork\Advanced Programing\Lab3LottoJSONProgram\WcfLottoService\WcfLottoServiceApp\Lotto.Json"));

        //set min/max vlaue of array to 1 and the json file value whcih is 29. ;
        int min = 1;
        int max = (int)myJsonFile["IrishLotto"];



        //declare and initilize an array with 6 values
        int[] randomNums = new int[6];

        //create new instance of Random 
        Random rand = new Random();

        //i starts at 0, keep looping whilst i is less than the lengh of the array which is 6, i + 1 after each loop
        for (int i = 0; i < randomNums.Length; i++)
        {
            //values are initially stored in tempNum to be checked against the current values in the array
            int tempNum = rand.Next(min, max);

            // IsDup is true, tempNum is the temporary 7th value in the array. ie. 
            //the array only stores 6 values but there is a 7th temporary number incase any of the initial 6 
            //values are the same. The 7th number will keep looping until it is unique and add to the array so there is 6 unique values. 
            while (IsDuplicate(tempNum, randomNums))
            {
                tempNum = rand.Next(7);
            }
            randomNums[i] = tempNum;

        }

        PrintTheArray(randomNums);

        return randomNums[0];


    }

    //Print the array to console to check if the numbers are gnerating and correct.
    private void PrintTheArray(int[]randomNums)
    {
        foreach (var item in randomNums)
        {
            Console.WriteLine(item);
        }
    }

    //This method returns true or false and checks whether the items in the array are a duplicate with the tempNum if yes then IsDup is true.
    public Boolean IsDuplicate(int tempNum, int[]randomNum)
    {
        foreach (var item in randomNum)
        {
            if (item == tempNum)
            {
                return true;
            }
        }
        return false;
    }
}
}

ILottoService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfLottoServiceApp
 {

//NOTE: You can use the "Rename" command on the "Refactor" menu to change   
the interface name "ILottoService" in both code and config file together.

[ServiceContract]
public interface ILottoService
{

    [OperationContract]

    int GenerateLottoDrawNums();

    [OperationContract]

    int GenerateIrishLottoNums();



}


}

FrontEndForm

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;

namespace Lotto_FrontEnd_Wcf_Json
{
public partial class FrontEnd : Form
{
    LottoServiceReference.LottoServiceClient ws = null;
    public FrontEnd()
    {
        InitializeComponent();
    }

    private void FrontEnd_Load(object sender, EventArgs e)
    {
        ws = new LottoServiceReference.LottoServiceClient();
    }

    private void btnLotto_Click(object sender, EventArgs e)
    {


    }

    private void btnIrishLotto_Click_1(object sender, EventArgs e)
    {

    }
}
}

JSON-файл

{
"LottoDraw": 59,


"IrishLotto": 29
}

В настоящий момент программа просто возвращает случайное значение при нажатии кнопки invoke при запуске wcf.Как только я смогу вернуть весь массив, я буду работать над печатью значений на этикетке в форме.

Причина, по которой я использую WCF и JSon, заключается в назначении, а не по выбору.

Я думаю, что я ошибаюсь, не передавая никаких параметров для [OperationContract]?

и, очевидно, я возвращаю только один элемент массива, но не могу понятькак вернуть все это.Я просто хотел увидеть, что это генерирует случайное число каждый раз, и когда я меняю randomNums [0] на [1], оно меняется, и это хорошо, верно?

И ничего не выводится на консоль, это делаетдействительно нужно, я только попробовал это и не вынул это.

Я думаю, что это понятно, извиняюсь, если это не так

Я только что узнал о wcf и json, поэтому мои знания чрезвычайно просты.

Любые советы или замечанияправильное направление очень ценится, заранее спасибо!

1 Ответ

0 голосов
/ 26 ноября 2018

Easy one.

Просто измените сигнатуру GenerateLottDrawNums, чтобы получить массив:

[OperationContract]
int[] GenerateLottoDrawNums();

И измените реализацию так, чтобы она возвращала весь массив, а не первый элемент

public int[] GenerateLottoDrawNums()
{
     // (...)
    //declare and initilize an array with 6 values
    int[] randomNums = new int[6];
    // (...)
    return randomNums;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...