Example #1
0
 public static void DeleteGruSysAPiJobSt(List<GruSysAPiJobSt> List)
 {
     using (WZNTServices.ServiceClient Client = new ServiceClient())
     {
         Client.DeleteGruSysAPiJobStList(List.ToArray());
     }
 }
        public static async Task StartRequestSubmitterAsync(string storageConnectionString, 
            string requestQueueName,
            string responseQueueName,
            int tps,
            int totalRequests)
        {
            var serviceClient = new ServiceClient<TestRequest, TestResponse>(
                storageConnectionString,
                new ServiceClientQueueNames
                {
                    RequestQueueName = requestQueueName,
                    ResponseQueueName = responseQueueName,
                },
                responseCheckFrequency: TimeSpan.FromSeconds(0.01));

            await serviceClient.InitializeQueuesAsync();

            var testServiceQueueSubmitter = new TestServiceQueueSubmitter(serviceClient);
            while (true)
            {
                try
                {
                    var requestSubmissionTask = testServiceQueueSubmitter.SubmitRequestsAsync(totalRequests, tps);
                    var stopwatch = Stopwatch.StartNew();
                    TimeSpan avgReqTime = await requestSubmissionTask;
                    TestRecorder.RecordAvgLatency(storageConnectionString, responseQueueName, avgReqTime, totalRequests,
                        tps, stopwatch.Elapsed);
                }
                catch (Exception ex)
                {
                    TestRecorder.LogException(storageConnectionString, responseQueueName, ex);
                }
            }
        }
 // GET: Game
 public ActionResult Index()
 {
     ServiceClient webService = new ServiceClient();
     ViewBag.Tournois = webService.GetTournois().Select(t => new SelectListItem { Text = t.Nom, Value = t.ID.ToString()});
     webService.Close();
     return View();
 }
Example #4
0
 //
 // GruArtAufEinSprache
 //
 public static List<GruArtAufEinSprache> GetListGruArtAufEinSprache(GruArtAufEinzelnutzen GruArtAufEinzelnutzen)
 {
     using (WZNTServices.ServiceClient Client = new ServiceClient())
     {
         return Client.ReadGruArtAufEinSpracheList(GruArtAufEinzelnutzen).ToList();
     }
 }
        public void WorkflowExtensionsBehaviorAddsExtension()
        {
            WorkflowServiceTestHost host = null;

            // TODO: Test with multiple extensions
            // TODO: Test with bad config file entries
            var serviceEndpoint1 = ServiceTest.GetUniqueEndpointAddress();
            using (host = WorkflowServiceTestHost.Open("ServiceExtensionTest.xamlx", serviceEndpoint1))
            {
                try
                {
                    var proxy = new ServiceClient(ServiceTest.Pipe, serviceEndpoint1);
                    try
                    {
                        proxy.GetData(1);
                        proxy.Close();
                    }
                    catch (Exception)
                    {
                        proxy.Abort();
                        throw;
                    }
                }
                finally
                {
                    if (host != null)
                    {
                        host.Tracking.Trace();
                    }
                }
            }
        }
 // GET: Match
 public ActionResult Index()
 {
     ServiceClient webService = new ServiceClient();
     ViewBag.Matchs = webService.GetMatchs();
     webService.Close();
     return View();
 }
Example #7
0
 public void Session_Start(object sender, EventArgs e)
 {
     ServiceClient sc = new ServiceClient();
     sc.Open();
     Session["ServiceClient"] = sc;
     Session["AuthStatus"] = false;
 }
        public ActionResult Index(string stockSymbol, string startDate, string endDate)
        {
            var client = new ServiceClient<IPriceDataService>();
            var list = client.Invoke(x => x.GetDaylineData(stockSymbol, Convert.ToDateTime(startDate), Convert.ToDateTime(endDate)));

            return View(list);
        }
Example #9
0
        public FileCollector(CacheManager cacheManager, FilesModel xmlString)
        {
            _cacheManager = cacheManager;


            // Create a required files object
            _requiredFiles = new RequiredFiles();


            foreach (var item in xmlString.Items)
            {
                _requiredFiles.Files.Add(item);
            }


            // Get the key for later use
            hardwareKey = new HardwareKey();

            // Make a new filelist collection
            _files = new Collection<RequiredFileModel>();

            // Create a webservice call
            xmdsFile = new ServiceClient();

            // Start up the Xmds Service Object
            //xmdsFile.Credentials = null;
            //xmdsFile.Url = Properties.Settings.Default.Client_xmds_xmds;
            //xmdsFile.UseDefaultCredentials = false;

            // Hook onto the xmds file complete event
            xmdsFile.GetFileCompleted += (XmdsFileGetFileCompleted);
        }
Example #10
0
 public static byte[] ObtenerImagen(string Nombre)
 {
     using (ServiceClient sc = new ServiceClient())
     {
         return sc.ObtenerImagenApp(Nombre);
     }
 }
        public ActionResult Index()
        {
            var client = new ServiceClient();
            client.Add(new Company {Id = 5, Name = "ABC Company", Address = "1234 Main Street"});

            return View();
        }
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                Service = new ServiceClient<ICustomerManagementService>(authorizationData);

                var user = await GetUserAsync(null);

                // Search for the accounts that matches the specified criteria.

                var accounts = await SearchAccountsByUserIdAsync(user.Id);

                PrintAccounts(accounts);
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Customer Management service exceptions
            catch (FaultException<Microsoft.BingAds.CustomerManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
Example #13
0
 public static IList<IList<string>> ObtenerAppsSuscripcion()
 {
     using (ServiceClient SCliente = new ServiceClient())
     {
         return SCliente.ObtenerAppsSuscripcion();
     }
 }
Example #14
0
 private void buttonSearch_Click(object sender, EventArgs e)
 {
     try
     {
         string userName = textBoxUserName.Text.Trim();
         if (userName.Equals(string.Empty))
         {
             ZBMMessageBox.ShowInfo("请输入用户名");
             return;
         }
         ServiceClient client = new ServiceClient();
         DataTable dataTable = client.SelectProjectByUser(userName);
         if (dataTable != null)
         {
             if (dataTable.Rows.Count > 0)
             {
                 dataGridViewProject.DataSource = dataTable;
             }
             else
             {
                 ZBMMessageBox.ShowInfo("此用户名下不存在项目");
             }
         }
         else
         {
             ZBMMessageBox.ShowInfo("查找失败");
         }
     }
     catch (Exception ex)
     {
         ExceptionLog.Instance.WriteLog(ex, LogType.UI);
         ZBMMessageBox.ShowError(ex);
     }
 }
 private void btnAddItem_Click(object sender, EventArgs e)
 {
     IService service = new ServiceClient();
     int id = Int32.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
     Item = service.GetItemFromID(id);
     this.Close();
 }
Example #16
0
        public void CallBackFunction(string functionType, string clientAddress, string functonName)
        {
            try
            {

            string s=string.Empty;
            if (functionType == "Identity")
            {
               MachineIdentity();
            }
            else  if (functionType == "GetFunction")
            {
                List<string> FunctionList= getFunctions();
                foreach (string fcn in FunctionList) // Loop through List with foreach.
                {
                    s=s+","+fcn;
                }
                InstanceContext context = new InstanceContext(this);
                proxy = new ServiceClient(context);
                proxy.UpdateData(s.TrimStart(','), clientAddress);
            }
            else if (functionType == "ExecuteFunction")
            {
                Console.WriteLine(functonName+" Command executed.");
            }

            }
            catch (Exception ex)
            {

                Program.logger.Error(ex.Message.ToString());
            }
        }
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                Service = new ServiceClient<ICustomerManagementService>(authorizationData);

                var getUserResponse = await GetUserAsync(null);
                var user = getUserResponse.User;

                // Search for the Bing Ads accounts that the user can access.

                var accounts = await SearchAccountsByUserIdAsync(user.Id);

                // Optionally if you are enabled for Final Urls, you can update each account with a tracking template.
                var accountFCM = new List<KeyValuePair<string, string>>();
                accountFCM.Add(new KeyValuePair<string, string>(
                    "TrackingUrlTemplate",
                    "http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}"));
                
                OutputStatusMessage("The user can access the following Bing Ads accounts: \n");
                foreach (var account in accounts)
                {
                    OutputAccount(account);

                    // Optionally you can find out which pilot features the customer is able to use. 
                    // Each account could belong to a different customer, so use the customer ID in each account.
                    var featurePilotFlags = await GetCustomerPilotFeaturesAsync((long)account.ParentCustomerId);
                    OutputStatusMessage("Customer Pilot flags:");
                    OutputStatusMessage(string.Join("; ", featurePilotFlags.Select(flag => string.Format("{0}", flag))));
                    
                    // Optionally if you are enabled for Final Urls, you can update each account with a tracking template.
                    // The pilot flag value for Final Urls is 194.
                    if (featurePilotFlags.Any(pilotFlag => pilotFlag == 194))
                    {
                        account.ForwardCompatibilityMap = accountFCM;
                        await UpdateAccountAsync(account);
                        OutputStatusMessage(string.Format("Updated the account with a TrackingUrlTemplate: {0}\n", 
                            accountFCM.ToArray().SingleOrDefault(keyValuePair => keyValuePair.Key == "TrackingUrlTemplate").Value));
                    }
                }
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Customer Management service exceptions
            catch (FaultException<Microsoft.BingAds.CustomerManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
 public void itemButton_Click(object sender, EventArgs e)
 {
     IService service = new ServiceClient();
     Form1 form1 = (Form1)ParentForm;
     int listNumber = Int32.Parse(((Button)sender).Tag.ToString());
     form1.ItemPanel.Visible = true;
     form1.ListPanel.Visible = false;
     form1.ItemPanel.shoppingListID = listNumber;
     ShoppingList sl = new ShoppingList();
     foreach (ShoppingList list in form1.p.shoppingLists)
     {
         if(list.ShoppingListNumber == listNumber)
         {
             sl = list;
         }
     }
     PartList[] pslArray = sl.PartLists;
     List<PartList> psl = pslArray.ToList();
     foreach (Person user in sl.Users)
     {
         if (user.Username != form1.p.Username)
         {
             form1.DgvPersons.Rows.Add(user.Name, user.Username);
         }
     }
     form1.ItemPanel.PopulatePanel(psl,sl);
     form1.TxtNote.Text = sl.Note;
     form1.Size = new System.Drawing.Size(1041, 598);
     form1.ItemPanel.BtnSaveList.Enabled = false;
 }
    /*Load information in the field and enables/disables textboxes and buttons
      according to which mode the page is opened
     NOTE: ItemId, PageMode and LastModified are hidden fiels in the page
     that stores the ID of current item, the mode which page is opened and the Last Update date
     of the record, once webpages are stateless*/
    protected void Page_Load(object sender, EventArgs e)
    {
        m_service = new ServiceClient();

        if(!IsPostBack)
        {
            ItemId.Value = Session["ID"].ToString();
            PageMode.Value = Session["Mode"].ToString();

            if (PageMode.Value == "Edit")
            {
                this.Page.Title = "Edit Item";
                LoadInfo();
                EnableControls(true);
                btnSubmit.Text = "Save";

            }
            else if (PageMode.Value == "View")
            {
                this.Page.Title = "View Details";
                LoadInfo();
                EnableControls(false);
            }

            if (PageMode.Value == "Add")
            {
                this.Page.Title = "Add New Item";
                txtID.Text = ItemId.Value;
                btnSubmit.Text = "Add";
                EnableControls(true);
            }
          }
    }
Example #20
0
        public GameBoardWPF(int gameId, int size, string gameOption, Player player1, Player player2, bool confirmationRequired)
        {
            c = new ServiceClient(new InstanceContext(this));
            this.boardSize = size;
            this.gameId = gameId;
            this.gameOption = gameOption;
            this.player1 = player1;
            this.player2 = player2;
            this.confirmationRequired = confirmationRequired;
            InitializeComponent();
            computerOrPlayer = gameOption;
            currenTurn = "player1";

            buttons1 = CreateButtons();
            buttons2 = CreateButtons();

            initGrid();

            if (!computerOrPlayer.Equals("computer") && !confirmationRequired) // if vs player - we need the other player to confirm the duel
            {
                busyIndicator.IsBusy = true;
                c.AskPlayerConfirmation(size,player1, player2,true,gameId);

            }
        }
Example #21
0
        public GameBoardWPF(int gameId, GameMove[] moves, bool confirmation)
        {
            InitializeComponent();
            c = new ServiceClient(new InstanceContext(this));
            this.gameId = gameId;
            this.moves = moves;
            this.confirmation = confirmation;
            boardSize = c.GetSizeGame(gameId);

            buttons1 = CreateButtons();

            initGrid();

            for (int i = 0; i < boardSize; i++)
            {
                for(int j = 0; j < boardSize; j++)
                {
                    buttons1[i, j].IsEnabled = false;
                }
            }

            // print all moves on game board
            for (int i = 0; i < moves.Count(); i++)
            {
                int row = Convert.ToInt32(moves[i].row);
                int col = Convert.ToInt32(moves[i].col);
                string s = moves[i].Sign;
                buttons1[row, col].Content = s;
                buttons1[row, col].FontSize = 50;
                buttons1[row, col].IsEnabled = false;
            }
        }
Example #22
0
 public IList<IList<string>> ObtenerPrimeros10Apps()
 {
     using (ServiceClient SCliente = new ServiceClient())
     {
         return SCliente.ObtenerAppsDeveloper(this.Correo);
     }
 }
 private static IEnumerable<TransactionInfo> GetAllTransactionsForUser(int window, int userId, int group, ServiceClient sc)
 {
     var Costs = sc.GetSplitCosts(group, userId, window).ToList();
     var Payments = sc.GetSplitPayments(group, userId, window).ToList();
     var allSplits = Costs.Union(Payments);
     return allSplits;
 }
        public void IncrementServiceShouldIncrementData()
        {
            // Arrange
            const int InitialData = 1;
            const int ExpectedData = 2;

            WorkflowServiceTestHost host = null;
            try
            {
                var address = ServiceTest.GetUniqueEndpointAddress();
                using (host = WorkflowServiceTestHost.Open("IncrementService.xamlx", address))
                {
                    var proxy = new ServiceClient(ServiceTest.Pipe, address);
                    int? value = InitialData;
                    proxy.Increment(ref value);
                    Assert.AreEqual(ExpectedData, value, "Increment did not correctly increment the value");
                }

                // The host must be closed before asserting tracking
                // Explicitly call host.Close or exit the using block to do this.

                // Assert that the Assign activity was executed with an argument named "Value" which contains the value 2
                host.Tracking.Assert.ExistsArgValue("Assign", ActivityInstanceState.Closed, "Value", 2);
            }
            finally
            {
                if (host != null)
                {
                    host.Tracking.Trace();
                }
            }
        }
Example #25
0
		public ActionResult Create(FormCollection collection) {
			try {
				ServiceReference.JediWS jedi = new JediWS();
				List<CaracteristiqueWS> caracList = new List<CaracteristiqueWS>();

				using(ServiceReference.ServiceClient service = new ServiceClient()) {
					service.getCaracteristiques().ForEach(x => {
						if(x.Type == ServiceReference.ETypeCaracteristiqueWS.Jedi) {
							caracList.Add(x);
						}
					});

					/* Item1. sur le champs du jedi parce que on a un tuple */
					jedi.Id = 0; // Car creation
					jedi.Nom = Convert.ToString(collection.Get("Item1.Nom"));
					jedi.IsSith = Convert.ToBoolean(collection.Get("Item1.IsSith") != "false"); // Pour que ca marche bien
					jedi.Caracteristiques = new List<CaracteristiqueWS>(); // Pour init

					string[] checkboxes = collection.GetValues("caracteristiques");
					if(checkboxes != null) {
						foreach(string s in checkboxes) {
							//On a que les ids des box selected, on ajoute les caracteristiques
							Int32 caracId = Convert.ToInt32(s);
							jedi.Caracteristiques.Add(caracList.First(x => x.Id == caracId));
						}
					}

					service.addJedi(jedi); // Ajout du jedi
				}

				return RedirectToAction("Index"); // Retour a l'index
			} catch {
				return RedirectToAction("Index");
			}
		}
Example #26
0
 public static void InsertGruSysAPiJobl(List<GruSysAPiJobl> List)
 {
     using (WZNTServices.ServiceClient Client = new ServiceClient())
     {
         Client.CreateGruSysAPiJoblList(List.ToArray());
     }
 }
Example #27
0
 public static void InsertGruSysStandort(List<GruSysStandort> List)
 {
     using (WZNTServices.ServiceClient Client = new ServiceClient())
     {
         Client.CreateGruSysStandortList(List.ToArray());
     }
 }
Example #28
0
 public void Actualizar(string Nombre, string Apellido, string Contrasegna)
 {
     using (ServiceClient SCliente = new ServiceClient())
     {
         SCliente.ActualizarDeveloper(Nombre, Apellido, this.Correo, Contrasegna);
     }
 }
Example #29
0
 public static void InsertGruArtAufEinzelnutzen(List<GruArtAufEinzelnutzen> List)
 {
     using (WZNTServices.ServiceClient Client = new ServiceClient())
     {
         Client.CreateGruArtAufEinzelnutzenList(List.ToArray());
     }
 }
Example #30
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack && !IsCallback)
     {
         service = new BJServiceRef.ServiceClient(new InstanceContext(new emptyCallback()),"HttpBinding");
     }
     if (Session["user"] == null)
         Server.Transfer("~/Default.aspx");
     currentUser = (UserWcf)Session["user"];
     if (!Page.IsCallback && !Page.IsPostBack)
     {
         selectedUser = currentUser;
         if (currentUser.isAdmin)
         {
             users = service.getUsers();
             rbl_users.DataSource = users;
             rbl_users.DataTextField = "Username";
             rbl_users.DataValueField = "Username";
             rbl_users.DataBind();
             Session["userlist"] = users;
         }
         populateFields();
     }
     if (Page.IsPostBack)
     {
         txt_username.Text = selectedUser.Username;
         selectedUser.money = int.Parse(txt_money.Text);
         selectedUser.numOfGames = int.Parse(txt_num_of_games.Text);
         selectedUser.isAdmin = chk_admin.Checked;
         
     }
     
     
     
 }
 public IoTCloudToDeviceAsyncCollector(ServiceClient serviceClient, IoTCloudToDeviceAttribute attribute)
 {
     // create client;
     IoTCloudToDeviceAsyncCollector.serviceClient = serviceClient;
 }
Example #32
0
        /// <summary>
        /// Generate NodeJS client code for given ServiceClient.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <returns></returns>
        public override async Task Generate(ServiceClient serviceClient)
        {
            var serviceClientTemplateModel = new ServiceClientTemplateModel(serviceClient);
            // Service client
            var serviceClientTemplate = new ServiceClientTemplate
            {
                Model = serviceClientTemplateModel,
            };

            await Write(serviceClientTemplate, serviceClient.Name.ToCamelCase() + ".js");

            if (!DisableTypeScriptGeneration)
            {
                var serviceClientTemplateTS = new ServiceClientTemplateTS
                {
                    Model = serviceClientTemplateModel,
                };
                await Write(serviceClientTemplateTS, serviceClient.Name.ToCamelCase() + ".d.ts");
            }

            //Models
            if (serviceClient.ModelTypes.Any())
            {
                var modelIndexTemplate = new ModelIndexTemplate
                {
                    Model = serviceClientTemplateModel
                };
                await Write(modelIndexTemplate, Path.Combine("models", "index.js"));

                if (!DisableTypeScriptGeneration)
                {
                    var modelIndexTemplateTS = new ModelIndexTemplateTS
                    {
                        Model = serviceClientTemplateModel
                    };
                    await Write(modelIndexTemplateTS, Path.Combine("models", "index.d.ts"));
                }

                foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels)
                {
                    var modelTemplate = new ModelTemplate
                    {
                        Model = modelType
                    };
                    await Write(modelTemplate, Path.Combine("models", modelType.Name.ToCamelCase() + ".js"));
                }
            }

            //MethodGroups
            if (serviceClientTemplateModel.MethodGroupModels.Any())
            {
                var methodGroupIndexTemplate = new MethodGroupIndexTemplate
                {
                    Model = serviceClientTemplateModel
                };
                await Write(methodGroupIndexTemplate, Path.Combine("operations", "index.js"));

                if (!DisableTypeScriptGeneration)
                {
                    var methodGroupIndexTemplateTS = new MethodGroupIndexTemplateTS
                    {
                        Model = serviceClientTemplateModel
                    };
                    await Write(methodGroupIndexTemplateTS, Path.Combine("operations", "index.d.ts"));
                }

                foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels)
                {
                    var methodGroupTemplate = new MethodGroupTemplate
                    {
                        Model = methodGroupModel
                    };
                    await Write(methodGroupTemplate, Path.Combine("operations", methodGroupModel.MethodGroupType.ToCamelCase() + ".js"));
                }
            }
        }
Example #33
0
 public AzureIoT()
 {
     s_serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString);
 }
Example #34
0
 public AzureFluentMethodTemplateModel(Method source, ServiceClient serviceClient)
     : base(source, serviceClient)
 {
     _namer = new AzureJavaFluentCodeNamer(serviceClient.Namespace);
 }
 public MetadataUtility(ServiceClient svcActions)
 {
     svcAct = svcActions;
 }
Example #36
0
 public ShowDivisionModel(ServiceClient client, BaseViewModel parent) : base(client, parent)
 {
     this.Subdivisions = client.GetDivisions();
 }
 public ConcentAgreementHelper()
 {
     _repository      = ObjectFactory.GetInstance <ExperianConsentAgreementRepository>();
     m_oServiceClient = new ServiceClient();
 }
Example #38
0
        // Invoke the direct method on the device, passing the payload
        public static async Task <int> InvokeMethod(string deviceId, string methodName, string content, ServiceClient s_serviceClient)
        {
            var methodInvocation = new CloudToDeviceMethod(methodName)
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson(JsonConvert.SerializeObject(content));

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await s_serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());

            return(response.Status);
        }
Example #39
0
 public override void InitializeServiceClient <T>(ServiceClient <T> client)
 {
     base.InitializeServiceClient(client);
 }
Example #40
0
 public IoTHubServiceClient(ServiceClient serviceClient, ILogger logger)
 {
     ServiceClient = serviceClient;
     Logger        = logger;
 }
Example #41
0
 /// <summary>
 /// Skips name collision resolution for method groups (operations) as they get
 /// renamed in template models.
 /// </summary>
 /// <param name="serviceClient"></param>
 /// <param name="exclusionDictionary"></param>
 protected override void ResolveMethodGroupNameCollision(ServiceClient serviceClient,
                                                         Dictionary <string, string> exclusionDictionary)
 {
     // Do nothing
 }
        /// <summary>
        /// Generates C# code for service client.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <returns></returns>
        public override async Task Generate(ServiceClient serviceClient)
        {
            // Service client
            var serviceClientTemplate = new AzureServiceClientTemplate
            {
                Model = new AzureServiceClientTemplateModel(serviceClient, InternalConstructors),
            };

            await Write(serviceClientTemplate, serviceClient.Name + ".cs");

            // Service client extensions
            var extensionsTemplate = new ExtensionsTemplate
            {
                Model = new AzureExtensionsTemplateModel(serviceClient, null),
            };

            await Write(extensionsTemplate, serviceClient.Name + "Extensions.cs");

            // Service client interface
            var serviceClientInterfaceTemplate = new ServiceClientInterfaceTemplate
            {
                Model = new AzureServiceClientTemplateModel(serviceClient, InternalConstructors),
            };

            await Write(serviceClientInterfaceTemplate, "I" + serviceClient.Name + ".cs");

            // Operations
            foreach (var group in serviceClient.MethodGroups)
            {
                // Operation
                var operationsTemplate = new AzureMethodGroupTemplate
                {
                    Model = new AzureMethodGroupTemplateModel(serviceClient, group),
                };
                await Write(operationsTemplate, operationsTemplate.Model.MethodGroupType + ".cs");

                // Service client extensions
                var operationExtensionsTemplate = new ExtensionsTemplate
                {
                    Model = new AzureExtensionsTemplateModel(serviceClient, group),
                };
                await Write(operationExtensionsTemplate, operationExtensionsTemplate.Model.ExtensionName + "Extensions.cs");

                // Operation interface
                var operationsInterfaceTemplate = new MethodGroupInterfaceTemplate
                {
                    Model = new AzureMethodGroupTemplateModel(serviceClient, group),
                };
                await Write(operationsInterfaceTemplate, "I" + operationsInterfaceTemplate.Model.MethodGroupType + ".cs");
            }

            // Models
            foreach (var model in serviceClient.ModelTypes.Concat(serviceClient.HeaderTypes))
            {
                if (model.Extensions.ContainsKey(AzureExtensions.ExternalExtension) &&
                    (bool)model.Extensions[AzureExtensions.ExternalExtension])
                {
                    continue;
                }

                var modelTemplate = new ModelTemplate
                {
                    Model = new AzureModelTemplateModel(model),
                };

                await Write(modelTemplate, Path.Combine("Models", model.Name + ".cs"));
            }

            // Enums
            foreach (var enumType in serviceClient.EnumTypes)
            {
                var enumTemplate = new EnumTemplate
                {
                    Model = new EnumTemplateModel(enumType),
                };
                await Write(enumTemplate, Path.Combine("Models", enumTemplate.Model.TypeDefinitionName + ".cs"));
            }

            // Page class
            foreach (var pageClass in pageClasses)
            {
                var pageTemplate = new PageTemplate
                {
                    Model = new PageTemplateModel(pageClass.Value, pageClass.Key.Key, pageClass.Key.Value),
                };
                await Write(pageTemplate, Path.Combine("Models", pageTemplate.Model.TypeDefinitionName + ".cs"));
            }

            // Exceptions
            foreach (var exceptionType in serviceClient.ErrorTypes)
            {
                if (exceptionType.Name == "CloudError")
                {
                    continue;
                }

                var exceptionTemplate = new ExceptionTemplate
                {
                    Model = new ModelTemplateModel(exceptionType),
                };
                await Write(exceptionTemplate, Path.Combine("Models", exceptionTemplate.Model.ExceptionTypeDefinitionName + ".cs"));
            }
        }
Example #43
0
        private void LoadPosition(PositionViewModel position)

        {
            Func <long, MediaListModel> selector = null;

            PositionViewModel model = position;

            MediaElement element = new MediaElement
            {
                LoadedBehavior = MediaState.Manual,

                Stretch = Stretch.Fill
            };

            if (model.Width.HasValue)

            {
                double?nullable4 = model.Width + 15.0;

                element.Width = (nullable4.Value / 768.0) * SystemParameters.PrimaryScreenWidth;
            }

            if (model.Height.HasValue)

            {
                double?nullable8 = model.Height + 15.0;

                element.Height = (nullable8.Value / 1366.0) * SystemParameters.PrimaryScreenHeight;
            }

            if (model.X.HasValue && model.Y.HasValue)

            {
                element.Margin = new Thickness((model.X.Value / 768.0) * SystemParameters.PrimaryScreenWidth, (model.Y.Value / 1366.0) * SystemParameters.PrimaryScreenHeight, 0.0, 0.0);
            }

            this.Playlist = new List <MediaListModel>();

            ServiceClient myService1 = new ServiceClient("BasicHttpBinding_IService", Constants.ServerAddress);

            try

            {
                if (selector == null)

                {
                    selector = media => new MediaListModel {
                        MediaID = media, DisplayLocation = myService1.GetMediaLocation(media), Duration = myService1.GetMediaDuration(media)
                    };
                }

                List <MediaListModel> list = position.Media; // position.Media.Select<long, MediaListModel>(selector).ToList<MediaListModel>();

                myService1.Close();

                List <MediaListModel> playlist = (from m in list select new MediaListModel {
                    MediaID = m.MediaID, DisplayLocation = m.DisplayLocation, Duration = m.Duration
                }).ToList <MediaListModel>();

                this.SavePositionMedia(position, playlist);

                this.MediaCanvas.Children.Add(element);

                Player player = new Player(this.Playlist, element);

                foreach (MediaListModel model2 in list.ToArray())

                {
                    PageSwitcher.DownloadMedium(model2, this.Playlist, player);
                }

                this.Players.Add(player);

                player.Start();
            }

            catch (Exception exception)

            {
                Console.WriteLine(exception.StackTrace + "\n\n" + exception.Message);
            }
        }
Example #44
0
 static void Main(string[] args)
 {
     serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
     ConnectCloud();
 }
Example #45
0
 /// <summary>
 /// Sends the data to a device registered in the IoT Hub
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public async Task SendMessageToDevice(string deviceId, string data)
 {
     ServiceClient serviceClient  = ServiceClient.CreateFromConnectionString(Strings.IoTHubConnectionString);
     var           commandMessage = new Message(Encoding.ASCII.GetBytes(data));
     await serviceClient.SendAsync(deviceId, commandMessage);
 }
        /// <summary>
        /// Adds the parameter groups to operation parameters.
        /// </summary>
        /// <param name="serviceClient"></param>
        public static void AddParameterGroups(ServiceClient serviceClient)
        {
            if (serviceClient == null)
            {
                throw new ArgumentNullException("serviceClient");
            }

            HashSet <CompositeType> generatedParameterGroups = new HashSet <CompositeType>();

            foreach (Method method in serviceClient.Methods)
            {
                //Copy out flattening transformations as they should be the last
                List <ParameterTransformation> flatteningTransformations = method.InputParameterTransformation.ToList();
                method.InputParameterTransformation.Clear();

                //This group name is normalized by each languages code generator later, so it need not happen here.
                IEnumerable <ParameterGroup> parameterGroups = ExtractParameterGroups(method);

                List <Parameter> parametersToAddToMethod      = new List <Parameter>();
                List <Parameter> parametersToRemoveFromMethod = new List <Parameter>();

                foreach (ParameterGroup parameterGroup in parameterGroups)
                {
                    CompositeType parameterGroupType =
                        generatedParameterGroups.FirstOrDefault(item => item.Name == parameterGroup.Name);

                    if (parameterGroupType == null)
                    {
                        IEnumerable <Method> methodsWhichUseGroup = GetMethodsUsingParameterGroup(serviceClient.Methods, parameterGroup);

                        parameterGroupType = new CompositeType
                        {
                            Name          = parameterGroup.Name,
                            Documentation = GenerateParameterGroupModelText(methodsWhichUseGroup)
                        };
                        generatedParameterGroups.Add(parameterGroupType);

                        //Add to the service client
                        serviceClient.ModelTypes.Add(parameterGroupType);
                    }

                    foreach (Property property in parameterGroup.ParameterMapping.Keys)
                    {
                        Property matchingProperty = parameterGroupType.Properties.FirstOrDefault(
                            item => item.Name == property.Name &&
                            item.IsReadOnly == property.IsReadOnly &&
                            item.DefaultValue == property.DefaultValue &&
                            item.SerializedName == property.SerializedName);
                        if (matchingProperty == null)
                        {
                            parameterGroupType.Properties.Add(property);
                        }
                    }

                    bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired);

                    //Create the new parameter object based on the parameter group type
                    Parameter newParameter = new Parameter()
                    {
                        Name           = parameterGroup.Name,
                        IsRequired     = isGroupParameterRequired,
                        Location       = ClientModel.ParameterLocation.None,
                        SerializedName = string.Empty,
                        Type           = parameterGroupType,
                        Documentation  = "Additional parameters for the operation"
                    };
                    parametersToAddToMethod.Add(newParameter);

                    //Link the grouped parameters to their parent, and remove them from the method parameters
                    foreach (Property property in parameterGroup.ParameterMapping.Keys)
                    {
                        Parameter p = parameterGroup.ParameterMapping[property];

                        var parameterTransformation = new ParameterTransformation
                        {
                            OutputParameter = p
                        };

                        parameterTransformation.ParameterMappings.Add(new ParameterMapping
                        {
                            InputParameter         = newParameter,
                            InputParameterProperty = property.GetClientName()
                        });
                        method.InputParameterTransformation.Add(parameterTransformation);
                        parametersToRemoveFromMethod.Add(p);
                    }
                }

                method.Parameters.RemoveAll(p => parametersToRemoveFromMethod.Contains(p));
                method.Parameters.AddRange(parametersToAddToMethod);

                // Copy back flattening transformations if any
                flatteningTransformations.ForEach(t => method.InputParameterTransformation.Add(t));
            }
        }
Example #47
0
        private string DeleteStudent(string id)
        {
            var student = new ServiceClient("Student");

            return(student.Delete(id));
        }
Example #48
0
        /// <summary>
        /// Resolves name collisions in the client model by iterating over namespaces (if provided,
        /// model names, client name, and client method groups.
        /// </summary>
        /// <param name="serviceClient">Service client to process.</param>
        /// <param name="clientNamespace">Client namespace or null.</param>
        /// <param name="modelNamespace">Client model namespace or null.</param>
        public virtual void ResolveNameCollisions(ServiceClient serviceClient, string clientNamespace,
                                                  string modelNamespace)
        {
            if (serviceClient == null)
            {
                throw new ArgumentNullException("serviceClient");
            }

            // take all namespaces of Models
            var exclusionListQuery = SplitNamespaceAndIgnoreLast(modelNamespace)
                                     .Union(SplitNamespaceAndIgnoreLast(clientNamespace));

            var exclusionDictionary = new Dictionary <string, string>(exclusionListQuery
                                                                      .Where(s => !string.IsNullOrWhiteSpace(s))
                                                                      .ToDictionary(s => s, v => "namespace"), StringComparer.OrdinalIgnoreCase);

            var models = new List <CompositeType>(serviceClient.ModelTypes);

            serviceClient.ModelTypes.Clear();
            foreach (var model in models)
            {
                model.Name = ResolveNameConflict(
                    exclusionDictionary,
                    model.Name,
                    "Schema definition",
                    "Model");

                serviceClient.ModelTypes.Add(model);
            }

            models = new List <CompositeType>(serviceClient.HeaderTypes);
            serviceClient.HeaderTypes.Clear();
            foreach (var model in models)
            {
                model.Name = ResolveNameConflict(
                    exclusionDictionary,
                    model.Name,
                    "Schema definition",
                    "Model");

                serviceClient.HeaderTypes.Add(model);
            }

            foreach (var model in serviceClient.ModelTypes
                     .Concat(serviceClient.HeaderTypes)
                     .Concat(serviceClient.ErrorTypes))
            {
                foreach (var property in model.Properties)
                {
                    if (property.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        property.Name += "Property";
                    }
                }
            }

            var enumTypes = new List <EnumType>(serviceClient.EnumTypes);

            serviceClient.EnumTypes.Clear();

            foreach (var enumType in enumTypes)
            {
                enumType.Name = ResolveNameConflict(
                    exclusionDictionary,
                    enumType.Name,
                    "Enum name",
                    "Enum");

                serviceClient.EnumTypes.Add(enumType);
            }

            serviceClient.Name = ResolveNameConflict(
                exclusionDictionary,
                serviceClient.Name,
                "Client",
                "Client");

            ResolveMethodGroupNameCollision(serviceClient, exclusionDictionary);
        }
        /// <summary>
        /// Generates Ruby code for Azure service client.
        /// </summary>
        /// <param name="serviceClient">The service client.</param>
        /// <returns>Async tasks which generates SDK files.</returns>
        public override async Task Generate(ServiceClient serviceClient)
        {
            var serviceClientTemplateModel = new AzureServiceClientTemplateModel(serviceClient);
            // Service client
            var serviceClientTemplate = new ServiceClientTemplate
            {
                Model = serviceClientTemplateModel
            };

            await Write(serviceClientTemplate, Path.Combine(sdkPath, RubyCodeNamer.UnderscoreCase(serviceClient.Name) + ImplementationFileExtension));

            // Operations
            foreach (var group in serviceClient.MethodGroups)
            {
                // Operation
                var operationsTemplate = new AzureMethodGroupTemplate
                {
                    Model = new AzureMethodGroupTemplateModel(serviceClient, group),
                };
                await Write(operationsTemplate, Path.Combine(sdkPath, RubyCodeNamer.UnderscoreCase(operationsTemplate.Model.MethodGroupName) + ImplementationFileExtension));
            }

            // Models
            foreach (var model in serviceClientTemplateModel.ModelTypes)
            {
                if ((model.Extensions.ContainsKey(AzureExtensions.ExternalExtension) &&
                     (bool)model.Extensions[AzureExtensions.ExternalExtension]) ||
                    model.Name == "Resource" || model.Name == "SubResource")
                {
                    continue;
                }

                var modelTemplate = new ModelTemplate
                {
                    Model = new AzureModelTemplateModel(model, serviceClient.ModelTypes),
                };
                await Write(modelTemplate, Path.Combine(modelsPath, RubyCodeNamer.UnderscoreCase(model.Name) + ImplementationFileExtension));
            }
            // Paged Models
            foreach (var pageModel in pageModels)
            {
                var pageTemplate = new PageModelTemplate
                {
                    Model = pageModel
                };
                await Write(pageTemplate, Path.Combine(modelsPath, RubyCodeNamer.UnderscoreCase(pageModel.Name) + ImplementationFileExtension));
            }

            // Enums
            foreach (var enumType in serviceClient.EnumTypes)
            {
                var enumTemplate = new EnumTemplate
                {
                    Model = new EnumTemplateModel(enumType),
                };
                await Write(enumTemplate, Path.Combine(modelsPath, RubyCodeNamer.UnderscoreCase(enumTemplate.Model.TypeDefinitionName) + ImplementationFileExtension));
            }

            // Requirements
            var requirementsTemplate = new RequirementsTemplate
            {
                Model = new AzureRequirementsTemplateModel(serviceClient, this.packageName ?? this.sdkName, this.ImplementationFileExtension, this.Settings.Namespace),
            };

            await Write(requirementsTemplate, RubyCodeNamer.UnderscoreCase(this.packageName ?? this.sdkName) + ImplementationFileExtension);

            // Version File
            if (this.packageVersion != null)
            {
                var versionTemplate = new VersionTemplate
                {
                    Model = new VersionTemplateModel(packageVersion),
                };
                await Write(versionTemplate, Path.Combine(sdkPath, "version" + ImplementationFileExtension));
            }

            // Module Definition File
            if (Settings.Namespace != null)
            {
                var modTemplate = new ModuleDefinitionTemplate
                {
                    Model = new ModuleDefinitionTemplateModel(Settings.Namespace),
                };
                await Write(modTemplate, Path.Combine(sdkPath, "module_definition" + ImplementationFileExtension));
            }
        }
Example #50
0
        private string CreateStudent(StudentsModel model)
        {
            var student = new ServiceClient("Student");

            return(student.Create(model));
        }
Example #51
0
        private string Create(AssignmentModel model)
        {
            var student = new ServiceClient("Assignment");

            return(student.Create(model));
        }
Example #52
0
        private string UpdateStudent(StudentsModel model)
        {
            var student = new ServiceClient("Student");

            return(student.Update(model, model.Id));
        }
Example #53
0
        /// <summary>
        /// Generates C# code for service client.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <returns></returns>
        public override async Task Generate(ServiceClient serviceClient)
        {
            // Service client
            var serviceClientTemplate = new ServiceClientTemplate
            {
                Model = new ServiceClientTemplateModel(serviceClient),
            };

            await Write(serviceClientTemplate, serviceClient.Name + ".cs");

            // Service client extensions
            var extensionsTemplate = new ExtensionsTemplate
            {
                Model = new ExtensionsTemplateModel(serviceClient, null),
            };

            await Write(extensionsTemplate, serviceClient.Name + "Extensions.cs");

            // Service client interface
            var serviceClientInterfaceTemplate = new ServiceClientInterfaceTemplate
            {
                Model = new ServiceClientTemplateModel(serviceClient),
            };

            await Write(serviceClientInterfaceTemplate, "I" + serviceClient.Name + ".cs");

            // Operations
            foreach (var group in serviceClient.MethodGroups)
            {
                // Operation
                var operationsTemplate = new MethodGroupTemplate
                {
                    Model = new MethodGroupTemplateModel(serviceClient, group),
                };
                await Write(operationsTemplate, operationsTemplate.Model.MethodGroupType + ".cs");

                // Service client extensions
                var operationExtensionsTemplate = new ExtensionsTemplate
                {
                    Model = new ExtensionsTemplateModel(serviceClient, group),
                };
                await Write(operationExtensionsTemplate, group + "Extensions.cs");

                // Operation interface
                var operationsInterfaceTemplate = new MethodGroupInterfaceTemplate
                {
                    Model = new MethodGroupTemplateModel(serviceClient, group),
                };
                await Write(operationsInterfaceTemplate, "I" + operationsInterfaceTemplate.Model.MethodGroupType + ".cs");
            }

            // Models
            foreach (var model in serviceClient.ModelTypes)
            {
                var modelTemplate = new ModelTemplate
                {
                    Model = new ModelTemplateModel(model),
                };
                await Write(modelTemplate, Path.Combine("Models", model.Name + ".cs"));
            }

            // Enums
            foreach (var enumType in serviceClient.EnumTypes)
            {
                var enumTemplate = new EnumTemplate
                {
                    Model = new EnumTemplateModel(enumType),
                };
                await Write(enumTemplate, Path.Combine("Models", enumTemplate.Model.TypeDefinitionName + ".cs"));
            }
        }
Example #54
0
        private string Update(AssignmentModel model)
        {
            var student = new ServiceClient("Assignment");

            return(student.Update(model, model.Id));
        }
Example #55
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddControllers()
            .AddNewtonsoftJson();

            services.AddInfrastructure();

            services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });

            services.AddDbContext <AccessControlContext>
                ((sp, options) =>
            {
                options.UseSqlServer(
                    sp.GetRequiredService <IConfiguration>().GetConnectionString("appservice-db"));
                options.EnableSensitiveDataLogging();
            })
            .AddIdentity <User, IdentityRole>()
            .AddEntityFrameworkStores <AccessControlContext>()
            .AddDefaultTokenProviders();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAnyOrigin",
                                  builder => builder
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
                {
                    policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                    policy.RequireClaim(ClaimTypes.NameIdentifier);
                });

                options.AddPolicy("AdministratorsOnly", policy => policy.RequireClaim("Administrator"));
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };

                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        if (!string.IsNullOrEmpty(accessToken) &&
                            (context.HttpContext.WebSockets.IsWebSocketRequest || context.Request.Headers["Accept"] == "text/event-stream"))
                        {
                            context.Token = context.Request.Query["access_token"];
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddOpenApiDocument();

            services.AddSingleton(sp => NotificationHubClient.CreateClientFromConnectionString(Configuration["Notifications:ConnectionString"], Configuration["Notifications:Path"]));
            services.AddSingleton(sp => ServiceClient.CreateFromConnectionString(Configuration["Hub:ConnectionString"]));
            services.AddSingleton(sp => EventHubClient.CreateFromConnectionString(Configuration["Events:ConnectionString"]));

            services.AddSingleton <DeviceController>();
            services.AddHostedService <AlarmService>();
            services.AddTransient <IJwtTokenService, JwtTokenService>();

            services.AddSingleton <IAccessLogNotifier, AccessLogNotifier>();
            services.AddSingleton <IAccessLogger, AccessLogger>();

            services.AddSignalR();

            services.AddMediatR(typeof(AuthCommand));
            //services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>));

            //services.AddValidatorsFromAssemblyContaining<LoginCommandValidator>();
        }
 public MainView(ServiceClient srv)
 {
     DataContext = new ViewModelMain(srv);
     InitializeComponent();
 }
Example #57
0
 public ShowCreditViewModel(ServiceClient repository, string displayName)
 {
     base.DisplayName = displayName;
     this.repository  = repository;
     CreateAllModel();
 }
Example #58
0
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new TextWriterTraceListener("console.log"));
            Trace.AutoFlush = true;

            instanceTime = DateTime.Now;

            conn = new SqlConnection("Server=tcp:juleeasia.database.windows.net,1433;Initial Catalog=iotdb;Persist Security Info=False;User ID=julee;Password=Passw0rd;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
            conn.Open();

            dvcSDKver = ".Net 1.0.2";
            svcSDKver = ".Net 1.0.3";

            //System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\julee\iothubperf.txt", true);

            Console.WriteLine("Start to send Cloud-to-Device message\n");
            serviceClient = ServiceClient.CreateFromConnectionString(serviceConnectionString);



            //you have to enable flag when sending message
            //ReceiveFeedbackAsync();

            //operations monitoring
            //operHubClient = EventHubClient.CreateFromConnectionString(operConnectionString, operEndpoint);
            //var operPartitions = operHubClient.GetRuntimeInformation().PartitionIds;
            //foreach (string partition in operPartitions)
            //{
            //    ReceiveMessagesFromMonitorAsync(partition);
            //}

            Console.Write("Enter the device ID:");
            deviceId = Console.ReadLine();
            //string deviceId = "demo";
            Console.Write("Enter the device SDK version:");
            dvcSDKver = Console.ReadLine();
            Console.Write("Enter a description:");
            desc = Console.ReadLine();

            //while (true)
            //{
            //receive용
            eventHubClient = EventHubClient.CreateFromConnectionString(eventhubconnectionString, iotHubD2cEndpoint);
            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            foreach (string partition in d2cPartitions)
            {
                ReceiveMessagesFromDeviceAsync(partition);
            }

            try
            {
                SendCloudToDeviceMessageAsync().Wait();
            }
            catch (Exception e)
            {
            }



            //    while (!commandProcessed)
            //    {
            //        if (commandReceived != "")
            //        {

            //            }
            //            commandReceived = "";



            //        }

            //        //no command received yet
            //        //Console.WriteLine("Command Not Received");
            //        Thread.Sleep(100);

            //        //if timeout occurred


            //    }

            //}
            Console.WriteLine("Program Running. Pless anykey to terminate!");
            Console.ReadLine();

            conn.Close();
        }
    public IServiceClient ServiceClient()
    {
        var wsClient = new ServiceClient();

        return(wsClient);
    }
Example #60
0
 public static async Task SendMessageToDeviceAsync(ServiceClient serviceClient, string targetDeviceId, string message)
 {
     var payload = new Message(Encoding.UTF8.GetBytes(message));
     await serviceClient.SendAsync(targetDeviceId, payload);
 }