private void DownloadFiles(List <EnvironmentViewModel> listOfEnvironments, List <FolderViewModel> listOfFolders) { this.ConsoleLog.WriteLog(Resource.DownloadStarted); downladTask = Task.Run(WebClientService.DowndLoadFiles(listOfEnvironments, listOfFolders, Filter, ConsoleLog, Progress)); downladTask.ContinueWith(GenerateNotification()); }
private async Task UploadToCloud(TelemetryData telemetry) { if (skiped == 6) { skiped = 0; try { var settings = SettingsService.Instance; var credential = settings.GetCredentialFromLocker(); if (!string.IsNullOrWhiteSpace(settings.WebHost) && credential != null) { var webclient = new WebClientService(settings.WebHost, credential.UserName, credential.Password); await webclient.Login(); var result = await webclient.SendTelemetryData(telemetry); Debug.WriteLine($"Result: {result}"); } } catch (Exception ex) { Debug.WriteLine(ex); } } else { skiped++; } }
public Form1(WebClientService webClientService, AppFileService appFileService) { InitializeComponent(); _webClientService = webClientService; _appFileService = appFileService; _appCurrentDirectory = Application.StartupPath; }
public object ModifyDtuRemoteConfigRequest([FromUri] int dtuId, [FromBody] DtuConfig dtuConfig) { // ET通信 ILog log = LogManager.GetLogger("DtuRemoteConfig"); log.DebugFormat("Instant DTU remote config: DTU={0}, dtuConfig={1}", dtuId, dtuConfig); // 设置消息头 Guid guid = Guid.NewGuid(); FsMessageHeader header = new FsMessageHeader { S = "WebClient", A = "GET", R = "/et/dtu/instant/at", // request url. U = guid, T = Guid.NewGuid() }; // 设置部分消息体 RemoteConfig rc = new RemoteConfig { Count = 2, Ip1 = dtuConfig.Ip, Port1 = dtuConfig.Port, Ip2 = dtuConfig.Ip2, Port2 = dtuConfig.Port2, Mode = dtuConfig.DtuMode.ToUpper(), ByteInterval = dtuConfig.PacketInterval, Retry = dtuConfig.ReconnectionCount }; List <CommandConfig> listCmd = RemoteConfigService.GetCommand(rc); FsMessage msg = new FsMessage { Header = header, Body = new { dtuId, cmds = listCmd } }; // return msg.Body; WebClientService.SendToET(msg); // 向ET Push DTU远程配置消息 using (var entity = new SecureCloud_Entities()) { var strGuid = guid.ToString(); var query = from ti in entity.T_TASK_INSTANT where ti.MSG_ID == strGuid select new { msgid = ti.MSG_ID }; var result = true; var list = query.ToList(); if (list.Count == 0) { result = false; } var json = new JObject( new JProperty("msgid", guid), new JProperty("result", result)); return(json); } }
public static bool IsAuthenticated() { if (!AuthTokenAvailable() && !AdminTokenAvailable()) { return(false); } var authToken = string.Empty; if (AdminTokenAvailable()) { authToken = GetAdminToken(); } else { authToken = GetAuthToken(); } var webClient = new WebClientService(new ConfigurationService()); var isAuthenticated = webClient.ExecutePost <bool>(new Models.ApiRequest() { EndPoint = "logins/isauthenticated", Request = authToken }); return(isAuthenticated); }
static void Main(string[] args) { Console.WriteLine("Starting..."); var settings = JObject .Parse(File.ReadAllText(@"config.json")) .ToObject <Settings>(); if (string.IsNullOrEmpty(settings.DiscordApiKey)) { Console.WriteLine("No API key provided"); Console.ReadKey(); return; } if (!string.IsNullOrEmpty(settings.UserToPing)) { Console.WriteLine("No user provided"); Console.ReadKey(); return; } webClient = new WebClientService(settings); var stockTask = Task.Run(async() => { await webClient.Init(); }); //Start the Import stockTask.Wait(); Console.WriteLine("done, press any key"); Console.ReadKey(); }
public void ExecuteAsync_ShouldBe_working() { var client = new RestClient(); WebClientService clientService = new WebClientService(client); var testModel = new TestJSonModel(); var result = clientService.ExecuteAsync <TestResponseModel>(testModel, "post", "http://wwww.google.com")?.Result; }
/// <summary> /// コンストラクタ /// </summary> /// <param name="playlistItem">プレイリストに所属する要素</param> public PlaylistItemViewModel(PlaylistItem playlistItem, PlaylistViewModel playlistViewModel) { PlaylistItem = playlistItem; PlaylistViewModel = playlistViewModel; Image = new ReactivePropertySlim <Avalonia.Media.Imaging.Bitmap>().AddTo(m_Disposables); var client = new WebClientService(); client.DownloadImage(PlaylistItem.Snippet.Thumbnails.Default__.Url, Image); }
/// <summary> /// コンストラクタ /// </summary> /// <param name="id">ID</param> /// <param name="title">タイトル</param> /// <param name="description">動画の概要</param> /// <param name="url">URL</param> public SearchResultItemViewModel(string id, string title, string description, string url) { Id = id; Title = title; Description = description; Image = new ReactivePropertySlim <Avalonia.Media.Imaging.Bitmap>().AddTo(m_Disposables); var client = new WebClientService(); client.DownloadImage(url, Image); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); // CorsConfig.RegisterCors(GlobalConfiguration.Configuration); log4net.Config.XmlConfigurator.Configure(); WebClientService.TryInit(this.Server.MapPath("~/bin/")); }
public static IHtmlString Pager(this HtmlHelper helper, string model, int?page, int?pageSize, string sort = null, string order = null, string search = null, Dictionary <string, object> otherQueryParams = null) { var webClient = new WebClientService(new ConfigurationService()); var count = webClient.ExecuteGet <int>(new Models.ApiRequest() { EndPoint = $"count?model={model}" }); var batches = count / pageSize; if ((count % pageSize) == 0 && count > 0) { batches--; } var htmlText = $"<div class='pageDescriptionDiv'>Page {((page != null && page > 0) ? page.ToString() : "1") } of { (batches > 0 ? (batches + 1).ToString() : "1") }</div>"; htmlText += "<ul class='boxingPager'>"; for (var i = 0; i <= batches; i++) { if ((i + 1) == page) { htmlText += "<li class='active'>"; htmlText += helper.ActionLink((i + 1).ToString(), "", "", new { href = "javascript:void(0)" }).ToString(); } else { htmlText += "<li>"; var routeValues = CreateRouteValues(i, pageSize, sort, order, search, otherQueryParams); htmlText += helper.ActionLink((i + 1).ToString(), "Index", routeValues).ToString(); } htmlText += "</li>"; } htmlText += "</ul>"; htmlText += helper.DropDownList("pageSize", new SelectList(new int[] { 10, 20, 50, 100 }), "Page Size: ", htmlAttributes: new { @class = "boxingDropDownList pageSizeDropDown" }).ToString(); return(MvcHtmlString.Create(htmlText)); }
private void SendMsg2ET(IList <SensorGroup> gp) { try { if (gp.Count() > 1) { // TODO WebClientService.SendToET(ConfigChangedMsgHelper.GetSensorGroupMessage()); } } catch (Exception ex) { log.ErrorFormat("SendMsg2ET error {0}", ex); } }
private void TryToInitializeWebClient() { try { var settings = SettingsService.Instance; var credential = settings.GetCredentialFromLocker(); if (!string.IsNullOrWhiteSpace(settings.WebHost) && credential != null) { webclient = new WebClientService(settings.WebHost, credential.UserName, credential.Password); } } catch (Exception ex) { Debug.WriteLine(ex); } }
public static bool CurrentUserIsAdmin() { if (!AdminTokenAvailable()) { return false; } var adminToken = GetAdminToken(); var webClient = new WebClientService(new ConfigurationService()); var hasAdminRights = webClient.ExecutePost<bool>(new Models.ApiRequest() { EndPoint = "logins/isauthenticated?adminRights=true", Request = adminToken }); return hasAdminRights; }
private Action <Task> GenerateNotification() { return((x) => { var state = WebClientService.GetState(); switch (state) { case EnumState.Finished: MessageBox.Show("All files are downloaded", "Notification", MessageBoxButton.OK, MessageBoxImage.Information); break; case EnumState.Stop: MessageBox.Show("The process has been stopped", "Notification", MessageBoxButton.OK, MessageBoxImage.Information); Reset(); break; } }); }
public static bool CurrentUserIsAdmin() { if (!AdminTokenAvailable()) { return(false); } var adminToken = GetAdminToken(); var webClient = new WebClientService(new ConfigurationService()); var hasAdminRights = webClient.ExecutePost <bool>(new Models.ApiRequest() { EndPoint = "logins/isauthenticated?adminRights=true", Request = adminToken }); return(hasAdminRights); }
public static IHtmlString Pager(this HtmlHelper helper, string model, int? page, int? pageSize, string sort = null, string order = null, string search = null, Dictionary<string, object> otherQueryParams = null) { var webClient = new WebClientService(new ConfigurationService()); var count = webClient.ExecuteGet<int>(new Models.ApiRequest() { EndPoint = $"count?model={model}" }); var batches = count / pageSize; if ((count % pageSize) == 0 && count > 0) { batches--; } var htmlText = $"<div class='pageDescriptionDiv'>Page {((page != null && page > 0) ? page.ToString() : "1") } of { (batches > 0 ? (batches + 1).ToString() : "1") }</div>"; htmlText += "<ul class='boxingPager'>"; for (var i = 0; i <= batches; i++) { if ((i + 1) == page) { htmlText += "<li class='active'>"; htmlText += helper.ActionLink((i + 1).ToString(), "", "", new { href = "javascript:void(0)" }).ToString(); } else { htmlText += "<li>"; var routeValues = CreateRouteValues(i, pageSize, sort, order, search, otherQueryParams); htmlText += helper.ActionLink((i + 1).ToString(), "Index", routeValues).ToString(); } htmlText += "</li>"; } htmlText += "</ul>"; htmlText += helper.DropDownList("pageSize", new SelectList(new int[] { 10, 20, 50, 100 }), "Page Size: ", htmlAttributes: new { @class = "boxingDropDownList pageSizeDropDown" }).ToString(); return MvcHtmlString.Create(htmlText); }
private void SendMsg2ET(IList <SensorGroup> newgp, IList <SensorGroup> oldgp) { try { if (newgp.Count() > 1 || oldgp.Count() > 1) { if (newgp.Count() != oldgp.Count() || !IsEqual(newgp, oldgp)) { // TODO WebClientService.SendToET(ConfigChangedMsgHelper.GetSensorGroupMessage()); } } } catch (Exception ex) { log.ErrorFormat("SendMsg2ET error {0}", ex); } }
public static UserDto GetCurrentUser() { var authToken = string.Empty; if (AdminTokenAvailable()) { authToken = GetAdminToken(); } else if (AuthTokenAvailable()) { authToken = GetAuthToken(); } else { return(null); } var webClient = new WebClientService(new ConfigurationService()); var logins = webClient.ExecuteGet <IEnumerable <LoginDto> >(new Models.ApiRequest() { EndPoint = "logins" }) ?.Select(q => new LoginsListItem() { Id = q.Id, AuthToken = q.AuthToken, ExpirationDate = q.ExpirationDate, UserId = q.UserId })?.ToList(); var currentLogin = logins?.FirstOrDefault(l => l.AuthToken == authToken); if (currentLogin == null) { return(null); } var users = webClient.ExecuteGet <IEnumerable <UserDto> >(new Models.ApiRequest() { EndPoint = "users" })?.ToList(); var currentUser = users.FirstOrDefault(u => u.Id == currentLogin.UserId); return(currentUser); }
static async Task Main(string[] args) { var clientService = new WebClientService(new WebClientServiceSettings("https://localhost:5001", string.Empty)); Console.WriteLine("Press ESC or CTRL-C to stop"); while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) { try { var forecast = await clientService.WeatherForecastClient.GetAsync(); } catch (System.Net.Http.HttpRequestException) { } await Task.Delay(1000); } Console.WriteLine("Closing.."); }
public object GetSensorRealtimeRequest(int dtu, string sensors) { log.DebugFormat("Instant DAC: DTU={0}, sensors={1}", dtu, sensors); Guid guid = Guid.NewGuid(); FsMessage msg = new FsMessage(); msg.Header.U = guid; msg.Header.R = "/et/dtu/instant/dac"; //request url. msg.Header.S = "WebClient"; msg.Header.M = "GET"; msg.Header.T = Guid.NewGuid(); msg.Body = new { dtu = dtu, sensors = ToIntArray(sensors), }; WebClientService.SendToET(msg); using (var entity = new SecureCloud_Entities()) { var strGuid = guid.ToString(); var query = from ti in entity.T_TASK_INSTANT where ti.MSG_ID == strGuid select new { msgid = ti.MSG_ID }; var result = true; var list = query.ToList(); if (list.Count == 0) { result = false; } var json = new JObject( new JProperty("msgid", guid), new JProperty("result", result)); return(json); } }
public object GetDtuRestartRequest(int dtuId) { var guid = Guid.NewGuid(); var msg = new FsMessage { Header = { S = "WebClient", A = "GET", R = "/et/dtu/instant/at-restart", U = guid, T = Guid.NewGuid() }, Body = new { dtuId } }; WebClientService.SendToET(msg); // 向ET Push DTU重启消息 using (var entity = new SecureCloud_Entities()) { var strGuid = guid.ToString(); var query = from ti in entity.T_TASK_INSTANT where ti.MSG_ID == strGuid select new { msgid = ti.MSG_ID }; var result = true; var list = query.ToList(); if (list.Count == 0) { result = false; } var json = new JObject( new JProperty("msgid", guid), new JProperty("result", result)); return(json); } }
public static bool IsAuthenticated() { if (!AuthTokenAvailable() && !AdminTokenAvailable()) { return false; } var authToken = string.Empty; if (AdminTokenAvailable()) { authToken = GetAdminToken(); } else { authToken = GetAuthToken(); } var webClient = new WebClientService(new ConfigurationService()); var isAuthenticated = webClient.ExecutePost<bool>(new Models.ApiRequest() { EndPoint = "logins/isauthenticated", Request = authToken }); return isAuthenticated; }
public HttpResponseMessage AddSensor([FromBody] Sensor model) { using (var db = new SecureCloud_Entities()) { try { var sensor = new T_DIM_SENSOR(); sensor.STRUCT_ID = model.StructId; sensor.SAFETY_FACTOR_TYPE_ID = model.FactorId; sensor.DTU_ID = model.DtuId; sensor.MODULE_NO = model.ModuleNo; sensor.DAI_CHANNEL_NUMBER = (byte?)model.Channel; sensor.PRODUCT_SENSOR_ID = model.ProductId; sensor.SENSOR_LOCATION_DESCRIPTION = model.Location; sensor.IsDeleted = false; sensor.Identification = model.Identify; sensor.Enable = model.Enable; var entry = db.Entry(sensor); entry.State = System.Data.EntityState.Added; var query = (from p in db.T_DIM_SENSOR_PRODUCT join fn in db.T_DIM_FORMULA_PARA on p.FORMAULAID equals fn.FormulaID into forluma from f in forluma.DefaultIfEmpty() join fname in db.T_DIM_FORMULA_PARA_NAME on f.ParaNameID equals fname.ParaNameID into name from n in name where p.PRODUCT_ID == model.ProductId orderby f.Order select f.FormulaParaID).ToList(); var para = (from q in query from v in model.Params where q == v.Id select new { q, v.Value }).ToList(); var old = from o in db.T_DIM_FORMULAID_SET where o.SENSOR_ID == sensor.SENSOR_ID select o; foreach (var o in old) { db.Entry(o).State = System.Data.EntityState.Deleted; } var newParam = new T_DIM_FORMULAID_SET(); newParam.SENSOR_ID = sensor.SENSOR_ID; for (int i = 0; i < para.Count(); i++) { newParam.GetType().GetProperty("FormulaParaID" + (i + 1)).SetValue(newParam, para[i].q, null); newParam.GetType().GetProperty("Parameter" + (i + 1)).SetValue(newParam, (decimal?)para[i].Value, null); } db.Entry(newParam).State = System.Data.EntityState.Added; if (model.CorrentId != null) { var correntSensor = new T_DIM_SENSOR_CORRENT(); var array = model.CorrentId.Split(','); for (int j = 0; j < array.Length; j++) { correntSensor.SensorId = sensor.SENSOR_ID; var correntId = array.GetValue(j); correntSensor.CorrentSensorId = Convert.ToInt32(correntId); db.T_DIM_SENSOR_CORRENT.Add(correntSensor); db.SaveChanges(); } } #region 日志信息 var fac = db.T_DIM_SAFETY_FACTOR_TYPE.Where(f => f.SAFETY_FACTOR_TYPE_ID == model.FactorId) .Select(f => f.SAFETY_FACTOR_TYPE_NAME) .FirstOrDefault(); var dtu = db.T_DIM_REMOTE_DTU.Where(d => d.ID == model.DtuId) .Select(d => d.REMOTE_DTU_NUMBER) .FirstOrDefault(); var pdt = db.T_DIM_SENSOR_PRODUCT.Where(p => p.PRODUCT_ID == model.ProductId) .Select(p => new { p.PRODUCT_NAME, p.PRODUCT_CODE }) .FirstOrDefault(); this.Request.Properties["ActionParameter"] = JsonConvert.SerializeObject(model); this.Request.Properties["ActionParameterShow"] = string.Format( "位置:{0},监测因素:{1},dtu:{2},模块号:{3},通道号:{4},设备类型:{5},参数:{6}", string.IsNullOrEmpty(model.Location) ? string.Empty : model.Location, fac ?? string.Empty, dtu ?? string.Empty, model.ModuleNo, model.Channel, pdt == null ? string.Empty : string.Format("{0}({1})", pdt.PRODUCT_NAME, pdt.PRODUCT_CODE), model.Params == null ? string.Empty : string.Join(",", model.Params.Select(p => p.Value))); #endregion db.SaveChanges(); if (sensor.Identification != 2) { Entity.Config.Sensor sensorinfo = GetSensor(sensor); var senopera = new SensorOperation { Action = Operations.Add, Sensor = sensorinfo, OldDtuId = sensorinfo.DtuID, OldSensorId = sensorinfo.SensorID }; WebClientService.SendToET(ConfigChangedMsgHelper.GetSensorConfigChangedMsg(senopera)); } return(Request.CreateResponse(HttpStatusCode.Accepted, StringHelper.GetMessageString("传感器新增成功"))); } catch (NullReferenceException e) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("传感器新增失败:参数无效"))); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.BadRequest, StringHelper.GetMessageString("传感器新增失败"))); } } }
public MessagesController() { webClientService = new WebClientService(new Uri("https://msging.net/messages"), "<your-api-key-here>"); }
public SubscriptionClient(WebClientService webClientService) { _webClientService = webClientService; _cache = new Cache(); }
public HttpResponseMessage Remove(int dtuId, int structId) { using (var entity = new SecureCloud_Entities()) { var dtuEntity = entity.T_DIM_REMOTE_DTU.FirstOrDefault(d => d.ID == dtuId); if (dtuEntity == null || dtuEntity.REMOTE_DTU_STATE == false) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("DTU不存在或已禁用"))); } // 检查传感器关联 var sens = entity.T_DIM_SENSOR.Where(s => s.DTU_ID == dtuId && !s.IsDeleted); if (sens.Any()) { return(Request.CreateResponse( HttpStatusCode.Conflict, StringHelper.GetMessageString("请先删除该DTU下的传感器"))); } // 删除关联 var sd = entity.T_DIM_STRUCT_DTU.Where(d => d.DtuId == dtuId && d.StructureId == structId); foreach (var m in sd) { entity.T_DIM_STRUCT_DTU.Remove(m); } // 检查关联 if (!entity.T_DIM_STRUCT_DTU.Any(d => d.DtuId == dtuId)) { dtuEntity.REMOTE_DTU_STATE = false; } #region 日志信息 var info = (from d in entity.T_DIM_REMOTE_DTU from s in entity.T_DIM_STRUCT_DTU from st in entity.T_DIM_STRUCTURE where d.ID == s.DtuId && d.ID == dtuId && s.StructureId == st.ID select new { d.REMOTE_DTU_NUMBER, st.STRUCTURE_NAME_CN }).FirstOrDefault(); var dtu = info == null ? string.Empty : info.REMOTE_DTU_NUMBER; var stc = info == null ? string.Empty : info.STRUCTURE_NAME_CN; this.Request.Properties["ActionParameterShow"] = string.Format("dtu号:{0}, 所属结构物:{1}", dtu, stc); #endregion try { var dtnod = new DtuNode { DtuId = (uint)dtuEntity.ID, Type = DtuType.Gprs, DtuCode = dtuEntity.REMOTE_DTU_NUMBER, Name = dtuEntity.DESCRIPTION, DacInterval = dtuEntity.REMOTE_DTU_GRANULARITY == null ? DtuNode.DefaultDacInterval : (uint)(dtuEntity.REMOTE_DTU_GRANULARITY * 60), NetworkType = dtuEntity.ProductDtuId == 2 ? NetworkType.hclocal : NetworkType.gprs }; if (dtnod.NetworkType == NetworkType.hclocal) { dtnod.AddProperty("param1", dtuEntity.P1); } entity.SaveChanges(); WebClientService.SendToET(ConfigChangedMsgHelper.GetDtuConfigChangedMsg(ChangedStatus.Delete, dtnod)); return(Request.CreateResponse( HttpStatusCode.Accepted, StringHelper.GetMessageString("DTU删除成功"))); } catch (Exception ex) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("DTU删除失败"))); } } }
public HttpResponseMessage Modify([FromUri] int dtuId, [FromBody] DtuModel dtu) { using (var entity = new SecureCloud_Entities()) { var dtuEntity = entity.T_DIM_REMOTE_DTU.FirstOrDefault(d => d.ID == dtuId); if (dtuEntity == null || dtuEntity.REMOTE_DTU_STATE == false) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("DTU不存在或已禁用"))); } StringBuilder sb = new StringBuilder(); string dtucode = dtuEntity.REMOTE_DTU_NUMBER; if (dtu.DtuNo != default(string) && dtu.DtuNo != dtuEntity.REMOTE_DTU_NUMBER) { dtuEntity.REMOTE_DTU_NUMBER = dtu.DtuNo; sb.AppendFormat("Dtu编号改为:{0},", dtu.DtuNo); } if (dtu.Granularity != default(int) && dtu.Granularity != dtuEntity.REMOTE_DTU_GRANULARITY) { dtuEntity.REMOTE_DTU_GRANULARITY = (short)dtu.Granularity; sb.AppendFormat("采集间隔改为:{0},", dtu.Granularity); } if (dtu.Sim != dtuEntity.REMOTE_DTU_SUBSCRIBER) { dtuEntity.REMOTE_DTU_SUBSCRIBER = dtu.Sim; sb.AppendFormat("sim卡号改为:{0},", dtu.Sim); } if (dtu.Ip != dtuEntity.DTU_IP) { dtuEntity.DTU_IP = dtu.Ip; sb.AppendFormat("Ip改为:{0},", dtu.Ip); } if (dtu.Port != dtuEntity.DTU_PORT) { dtuEntity.DTU_PORT = dtu.Port; sb.AppendFormat("端口改为:{0},", dtu.Port); } if (dtu.ProductId != default(int) && dtu.ProductId != dtuEntity.ProductDtuId) { dtuEntity.ProductDtuId = dtu.ProductId; var product = entity.T_DIM_DTU_PRODUCT.FirstOrDefault(p => p.ProductId == dtu.ProductId); if (product != null) { sb.AppendFormat("产品厂商改为{0},型号改为:{1}", product.DtuFactory, product.DtuModel); } else { sb.AppendFormat("产品id改为{0}", dtu.ProductId); } } if (dtu.P1 != dtuEntity.P1) { dtuEntity.P1 = dtu.P1; sb.AppendFormat("参数1改为:{0}", dtu.P1); } if (dtu.P2 != dtuEntity.P2) { dtuEntity.P2 = dtu.P2; sb.AppendFormat("参数2改为:{0}", dtu.P1); } if (dtu.P3 != dtuEntity.P3) { dtuEntity.P3 = dtu.P3; sb.AppendFormat("参数3改为:{0}", dtu.P1); } if (dtu.P4 != dtuEntity.P4) { dtuEntity.P4 = dtu.P4; sb.AppendFormat("参数4改为:{0}", dtu.P1); } #region 日志信息 this.Request.Properties["ActionParameter"] = JsonConvert.SerializeObject(dtu); this.Request.Properties["ActionParameterShow"] = string.Format("dtu号:{0}:{1}", dtu.DtuNo ?? string.Empty, sb); #endregion try { entity.SaveChanges(); var dtnod = new DtuNode { DtuId = (uint)dtuEntity.ID, Type = DtuType.Gprs, DtuCode = dtuEntity.REMOTE_DTU_NUMBER, NetworkType = dtuEntity.ProductDtuId == 2 ? NetworkType.hclocal : NetworkType.gprs, Name = dtuEntity.DESCRIPTION, DacInterval = dtuEntity.REMOTE_DTU_GRANULARITY == null ? DtuNode.DefaultDacInterval : (uint)dtuEntity.REMOTE_DTU_GRANULARITY }; if (dtnod.NetworkType == NetworkType.hclocal) { dtnod.AddProperty("param1", dtuEntity.P1); } WebClientService.SendToET(ConfigChangedMsgHelper.GetDtuConfigChangedMsg(ChangedStatus.Modify, dtnod, dtucode)); return(Request.CreateResponse( HttpStatusCode.Accepted, StringHelper.GetMessageString("DTU信息修改成功"))); } catch (Exception ex) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("DTU信息修改失败"))); } } }
public HttpResponseMessage Add([FromBody] DtuModel dtu) { using (var entity = new SecureCloud_Entities()) { // 新增dtu var dtuEntity = new T_DIM_REMOTE_DTU(); dtuEntity.REMOTE_DTU_NUMBER = dtu.DtuNo; dtuEntity.REMOTE_DTU_SUBSCRIBER = dtu.Sim; dtuEntity.REMOTE_DTU_GRANULARITY = (short)dtu.Granularity; dtuEntity.DTU_IP = dtu.Ip; dtuEntity.DTU_PORT = dtu.Port; dtuEntity.P1 = dtu.P1; dtuEntity.P2 = dtu.P2; dtuEntity.P3 = dtu.P3; dtuEntity.P4 = dtu.P4; dtuEntity.ProductDtuId = dtu.ProductId; dtuEntity.REMOTE_DTU_STATE = true; var entry = entity.Entry(dtuEntity); entry.State = System.Data.EntityState.Added; // 添加关联关系 var sdEntity = new T_DIM_STRUCT_DTU(); sdEntity.DtuId = dtuEntity.ID; sdEntity.StructureId = dtu.StructId; var entry2 = entity.Entry(sdEntity); entry2.State = System.Data.EntityState.Added; #region 日志信息 var stc = entity.T_DIM_STRUCTURE.FirstOrDefault(s => s.ID == dtu.StructId); var product = entity.T_DIM_DTU_PRODUCT.FirstOrDefault(p => p.ProductId == dtu.ProductId); var paramName1 = (product != null && product.NetworkType.ToLower().Contains("local")) ? "文件路径" : "参数1"; this.Request.Properties["ActionParameter"] = JsonConvert.SerializeObject(dtu); this.Request.Properties["ActionParameterShow"] = string.Format( "dtu号:{0},结构物:{1},采集粒度:{3},产品厂商:{6},产品型号:{7},sim卡号:{2},ip地址:{4},端口:{5},[{12}:{8},参数2:{9},参数3:{10},参数4:{11}]", dtu.DtuNo ?? string.Empty, stc == null ? string.Empty : stc.STRUCTURE_NAME_CN, dtu.Sim ?? string.Empty, dtu.Granularity, dtu.Ip, dtu.Port, product != null ? product.DtuFactory : string.Empty, product != null ? product.DtuModel : string.Empty, dtu.P1, dtu.P2, dtu.P3, dtu.P4, paramName1); #endregion try { entity.SaveChanges(); var dtnod = new DtuNode { DtuId = (uint)dtuEntity.ID, Type = DtuType.Gprs, DtuCode = dtuEntity.REMOTE_DTU_NUMBER, Name = dtuEntity.DESCRIPTION, DacInterval = dtuEntity.REMOTE_DTU_GRANULARITY == null ? DtuNode.DefaultDacInterval : (uint)(dtuEntity.REMOTE_DTU_GRANULARITY * 60), NetworkType = dtuEntity.ProductDtuId == 2 ? NetworkType.hclocal : NetworkType.gprs }; if (dtnod.NetworkType == NetworkType.hclocal) { dtnod.AddProperty("param1", dtuEntity.P1); } WebClientService.SendToET(ConfigChangedMsgHelper.GetDtuConfigChangedMsg(ChangedStatus.Add, dtnod)); return(Request.CreateResponse( HttpStatusCode.Accepted, StringHelper.GetMessageString("添加DTU成功"))); } catch (Exception ex) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("添加DTU失败"))); } } }
public CommonController(ILogger <CommonController> logger, WebClientService client) { _logger = logger; this.client = client; }
public static UserDto GetCurrentUser() { var authToken = string.Empty; if (AdminTokenAvailable()) { authToken = GetAdminToken(); } else if (AuthTokenAvailable()) { authToken = GetAuthToken(); } else { return null; } var webClient = new WebClientService(new ConfigurationService()); var logins = webClient.ExecuteGet<IEnumerable<LoginDto>>(new Models.ApiRequest() { EndPoint = "logins" }) ?.Select(q => new LoginsListItem() { Id = q.Id, AuthToken = q.AuthToken, ExpirationDate = q.ExpirationDate, UserId = q.UserId })?.ToList(); var currentLogin = logins?.FirstOrDefault(l => l.AuthToken == authToken); if (currentLogin == null) { return null; } var users = webClient.ExecuteGet<IEnumerable<UserDto>>(new Models.ApiRequest() { EndPoint = "users" })?.ToList(); var currentUser = users.FirstOrDefault(u => u.Id == currentLogin.UserId); return currentUser; }
public HttpResponseMessage ModifySensor([FromUri] int sensorId, [FromBody] Sensor model) { using (var db = new SecureCloud_Entities()) { try { var sensor = db.T_DIM_SENSOR.FirstOrDefault(s => s.SENSOR_ID == sensorId && !s.IsDeleted); if (sensor == null) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("传感器修改失败:传感器不存在或已删除"))); } int dtuid = sensor.DTU_ID.Value; StringBuilder sb = new StringBuilder(); var sensorLoc = sensor.SENSOR_LOCATION_DESCRIPTION; sb.AppendFormat("原传感器:{0}:", sensorLoc); if (model.FactorId != default(int) && model.FactorId != sensor.SAFETY_FACTOR_TYPE_ID) { sensor.SAFETY_FACTOR_TYPE_ID = model.FactorId; var fac = db.T_DIM_SAFETY_FACTOR_TYPE.Where(f => f.SAFETY_FACTOR_TYPE_ID == model.FactorId) .Select(f => f.SAFETY_FACTOR_TYPE_NAME) .FirstOrDefault(); sb.AppendFormat("监测因素改为:{0};", fac); } if (model.DtuId != default(int) && model.DtuId != sensor.DTU_ID) { sensor.DTU_ID = model.DtuId; var dtu = db.T_DIM_REMOTE_DTU.Where(d => d.ID == model.DtuId) .Select(d => d.REMOTE_DTU_NUMBER) .FirstOrDefault(); sb.AppendFormat("dtu号改为:{0};", dtu); } if (model.ModuleNo != default(int) && model.ModuleNo != sensor.MODULE_NO) { sensor.MODULE_NO = model.ModuleNo; sb.AppendFormat("模块号改为:{0};", model.ModuleNo); } if (model.Channel != null && model.Channel != sensor.DAI_CHANNEL_NUMBER) { sensor.DAI_CHANNEL_NUMBER = (byte?)model.Channel; sb.AppendFormat("通道改为:{0};", model.Channel); } //2-26 if (model.Enable != sensor.Enable) { sensor.Enable = model.Enable; sb.AppendFormat("使能改为:{0};", model.Enable); } if (model.ProductId != default(int) && model.ProductId != sensor.PRODUCT_SENSOR_ID) { sensor.PRODUCT_SENSOR_ID = model.ProductId; var pdt = db.T_DIM_SENSOR_PRODUCT.Where(p => p.PRODUCT_ID == model.ProductId) .Select(p => new { p.PRODUCT_NAME, p.PRODUCT_CODE }) .FirstOrDefault(); sb.AppendFormat("设备改为{0}({1});", pdt.PRODUCT_NAME, pdt.PRODUCT_CODE); } if (model.Location != default(string) && model.Location != sensor.SENSOR_LOCATION_DESCRIPTION) { sensor.SENSOR_LOCATION_DESCRIPTION = model.Location; sb.AppendFormat("位置标识改为{0};", model.Location); } if (model.Params != null) { var query = (from p in db.T_DIM_SENSOR_PRODUCT join fn in db.T_DIM_FORMULA_PARA on p.FORMAULAID equals fn.FormulaID into forluma from f in forluma.DefaultIfEmpty() join fname in db.T_DIM_FORMULA_PARA_NAME on f.ParaNameID equals fname.ParaNameID into name from n in name where p.PRODUCT_ID == model.ProductId orderby f.Order select new { f.FormulaParaID, n.ParaAlias }).ToList(); var para = (from q in query from v in model.Params where q.FormulaParaID == v.Id select new { q.FormulaParaID, v.Value }).ToList(); var paramStr = (from q in query from v in model.Params where q.FormulaParaID == v.Id select new { q.ParaAlias, v.Value }).ToList(); sb.AppendFormat( "参数修改为:{0}", string.Join( "-", paramStr.Select(p => string.Format("{0}:{1}", p.ParaAlias, p.Value)).ToArray())); var old = from o in db.T_DIM_FORMULAID_SET where o.SENSOR_ID == sensor.SENSOR_ID select o; foreach (var o in old) { db.Entry(o).State = System.Data.EntityState.Deleted; } var newParam = new T_DIM_FORMULAID_SET(); newParam.SENSOR_ID = sensor.SENSOR_ID; for (int i = 0; i < para.Count(); i++) { newParam.GetType() .GetProperty("FormulaParaID" + (i + 1)) .SetValue(newParam, para[i].FormulaParaID, null); newParam.GetType() .GetProperty("Parameter" + (i + 1)) .SetValue(newParam, (decimal?)para[i].Value, null); } db.Entry(newParam).State = System.Data.EntityState.Added; } //关联传感器 if (model.CorrentId != null) { var correntTable = from cp in db.T_DIM_SENSOR_CORRENT where cp.SensorId == sensorId select cp; foreach (var o in correntTable) { db.T_DIM_SENSOR_CORRENT.Remove(o); } var array = model.CorrentId.Split(','); for (int j = 0; j < array.Length; j++) { var correntSensor = new T_DIM_SENSOR_CORRENT(); correntSensor.SensorId = sensorId; var correntId = array.GetValue(j); correntSensor.CorrentSensorId = Convert.ToInt32(correntId); db.T_DIM_SENSOR_CORRENT.Add(correntSensor); db.SaveChanges(); } } #region 日志信息 this.Request.Properties["ActionParameter"] = JsonConvert.SerializeObject(model); this.Request.Properties["ActionParameterShow"] = sb.ToString(); #endregion db.SaveChanges(); if (sensor.Identification != 2) { Entity.Config.Sensor sensorinfo = GetSensor(sensor); var senopera = new SensorOperation { Sensor = sensorinfo, OldDtuId = (uint)dtuid, OldSensorId = sensorinfo.SensorID, Action = sensor.DTU_ID == dtuid ? Operations.Update : Operations.ChangedDtu }; WebClientService.SendToET(ConfigChangedMsgHelper.GetSensorConfigChangedMsg(senopera)); } return(Request.CreateResponse(HttpStatusCode.Accepted, StringHelper.GetMessageString("传感器修改成功"))); } catch (NullReferenceException e) { return(Request.CreateResponse( HttpStatusCode.BadRequest, StringHelper.GetMessageString("传感器修改失败:参数无效"))); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.BadRequest, StringHelper.GetMessageString("传感器修改失败"))); } } }
public HttpResponseMessage RemoveSensor([FromUri] int sensorId) { using (var db = new SecureCloud_Entities()) { var sensor = db.T_DIM_SENSOR.FirstOrDefault(s => s.SENSOR_ID == sensorId && !s.IsDeleted); if (sensor == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, StringHelper.GetMessageString("传感器不存在"))); } sensor.MODULE_NO *= -1; sensor.DAI_CHANNEL_NUMBER = (byte)(sensor.DAI_CHANNEL_NUMBER * -1); sensor.IsDeleted = true; //表T_DIM_SENSOR_CORRENT的同步变动 IQueryable <T_DIM_SENSOR_CORRENT> Corrent = from p in db.T_DIM_SENSOR_CORRENT where p.SensorId == sensorId || p.CorrentSensorId == sensorId//反向删除 select p; foreach (var CorrentConfig in Corrent) { db.T_DIM_SENSOR_CORRENT.Remove(CorrentConfig); } #region 日志信息 this.Request.Properties["ActionParameterShow"] = "传感器位置:" + sensor.SENSOR_LOCATION_DESCRIPTION; #endregion try { if (sensor.Identification != 2) { var sensorinfo = new Entity.Config.Sensor { DtuID = sensor.DTU_ID == null ? 0 : (uint)sensor.DTU_ID, SensorID = (uint)sensor.SENSOR_ID, StructId = sensor.STRUCT_ID == null ? 0 : (uint)sensor.STRUCT_ID, ModuleNo = sensor.MODULE_NO == null ? 0 : (uint)sensor.MODULE_NO, ChannelNo = sensor.DAI_CHANNEL_NUMBER == null ? 0 : (uint)sensor.DAI_CHANNEL_NUMBER, Name = sensor.SENSOR_LOCATION_DESCRIPTION, UnEnable = sensor.Enable//3-3 }; var senopera = new SensorOperation { Action = Operations.Delete, OldDtuId = sensorinfo.DtuID, OldSensorId = sensorinfo.SensorID, Sensor = sensorinfo }; WebClientService.SendToET(ConfigChangedMsgHelper.GetSensorConfigChangedMsg(senopera)); } db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Accepted, StringHelper.GetMessageString("传感器删除成功"))); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.BadRequest, StringHelper.GetMessageString("传感器删除失败"))); } } }
public SubscriptionClient(string endpoint, string authorizationToken, int cacheTimeoutInSeconds = 300) { _webClientService = new WebClientService(endpoint, authorizationToken); _cache = new Cache(cacheTimeoutInSeconds); }