private async Task <InvokeResult> SendServiceBusMessage(MessageTransmissionPlan plan) { var messageTemplate = plan.Message.Value; if (String.IsNullOrEmpty(_simulator.DefaultEndPoint)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Default End Point is Missing to send to Service Bus."); return(InvokeResult.FromError("Default End Point is Missing to send to Event Hub.")); } if (String.IsNullOrEmpty(_simulator.AccessKeyName)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Access Key Name is Missing to send to Service Bus."); return(InvokeResult.FromError("Access Key Name is Missing to send to Event Hub.")); } if (String.IsNullOrEmpty(_simulator.QueueName)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Queue Name is Missing to send to Service Bus."); return(InvokeResult.FromError("Queue Name is Missing to send to Event Hub.")); } if (String.IsNullOrEmpty(_simulator.AccessKey)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Access Key is Missing to send to Service Bus."); return(InvokeResult.FromError("Access Key is Missing to send to Event Hub.")); } var connectionString = $"Endpoint=sb://{_simulator.DefaultEndPoint}.servicebus.windows.net/;SharedAccessKeyName={_simulator.AccessKeyName};SharedAccessKey={_simulator.AccessKey}"; var bldr = new ServiceBusConnectionStringBuilder(connectionString) { EntityPath = messageTemplate.QueueName }; var client = new QueueClient(bldr, ReceiveMode.PeekLock, Microsoft.Azure.ServiceBus.RetryExponential.Default); var msg = new Microsoft.Azure.ServiceBus.Message() { Body = GetMessageBytes(plan), To = messageTemplate.To, ContentType = messageTemplate.ContentType }; if (!String.IsNullOrEmpty(msg.MessageId)) { msg.MessageId = msg.MessageId; } await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending message to Service Bus {_simulator.DefaultEndPoint}"); await client.SendAsync(msg); await client.CloseAsync(); ReceivedContent = $"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessagePublished}"; await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent); return(InvokeResult.Success); }
private async Task <InvokeResult> SendRESTRequestAsync(MessageTransmissionPlan plan) { var messageTemplate = plan.Message.Value; if (messageTemplate.PayloadType.Id == MessageTemplate.PayloadTypes_GeoPath) { return(await SendHTMLGeoMessage(plan)); } using (var client = new HttpClient()) { var protocol = messageTemplate.Transport.Value == TransportTypes.RestHttps ? "https" : "http"; String uri = null; /*if (!String.IsNullOrEmpty(messageTemplate.EndPoint)) * { * uri = $"{protocol}://{messageTemplate.EndPoint}:{messageTemplate.Port}{ReplaceTokens(_instance, plan, messageTemplate.PathAndQueryString)}"; * } * else */ if (!String.IsNullOrEmpty(_simulator.DefaultEndPoint)) { uri = $"{protocol}://{_simulator.DefaultEndPoint}:{_simulator.DefaultPort}{ReplaceTokens(_instance, plan, messageTemplate.PathAndQueryString)}"; } if (String.IsNullOrEmpty(uri)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "End Point must be provided at the Simulator or Message Level"); return(InvokeResult.FromError("End Point must be provided at the Simulator or Message Level")); } if (!_simulator.Anonymous) { if (_simulator.BasicAuth) { if (String.IsNullOrEmpty(_simulator.Password) || String.IsNullOrEmpty(_simulator.UserName)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Simulator is not anonymous however user name and password not supplied for basic auth."); return(InvokeResult.FromError("Simulator is not anonymous however user name and password not supplied for basic auth.")); } var authCreds = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_simulator.UserName + ":" + _simulator.Password)); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authCreds); } else { if (String.IsNullOrEmpty(_simulator.AuthHeader)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Simulator is not anonymous however auth header is not provided and not basic auth."); return(InvokeResult.FromError("Simulator is not anonymous however auth header is not provided and not basic auth..")); } client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(_simulator.AuthHeader); } } System.Net.Http.HttpResponseMessage responseMessage = null; foreach (var hdr in messageTemplate.MessageHeaders) { client.DefaultRequestHeaders.Add(hdr.HeaderName, ReplaceTokens(_instance, plan, hdr.Value)); } await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending: {messageTemplate.HttpVerb} to {uri}."); var messageBody = ReplaceTokens(_instance, plan, messageTemplate.TextPayload); try { switch (messageTemplate.HttpVerb) { case MessageTemplate.HttpVerb_GET: responseMessage = await client.GetAsync(uri); break; case MessageTemplate.HttpVerb_POST: responseMessage = await client.PostAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType)); break; case MessageTemplate.HttpVerb_PUT: responseMessage = await client.PutAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType)); break; case MessageTemplate.HttpVerb_DELETE: responseMessage = await client.DeleteAsync(uri); break; default: await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Unknown HTTP Verb [{messageTemplate.HttpVerb}]"); return(InvokeResult.FromError($"Unknown HTTP Verb [{messageTemplate.HttpVerb}]")); } } catch (HttpRequestException ex) { var fullResponseString = new StringBuilder(); fullResponseString.AppendLine(ex.Message); if (ex.InnerException != null) { fullResponseString.AppendLine(ex.InnerException.Message); } await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending message: {ex.Message}."); ReceivedContent = fullResponseString.ToString(); return(InvokeResult.FromException("SendRESTRequestAsync", ex)); } if (responseMessage.IsSuccessStatusCode) { var responseContent = await responseMessage.Content.ReadAsStringAsync(); var fullResponseString = new StringBuilder(); fullResponseString.AppendLine($"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessageSent}"); fullResponseString.AppendLine($"Response Code: {(int)responseMessage.StatusCode} ({responseMessage.ReasonPhrase})"); foreach (var hdr in responseMessage.Headers) { fullResponseString.AppendLine($"{hdr.Key}\t:{hdr.Value.FirstOrDefault()}"); } fullResponseString.AppendLine(); fullResponseString.Append(responseContent); ReceivedContent = fullResponseString.ToString(); if (ReceivedContent.Length > 255) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent.Substring(0, 250)); } else { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent); } await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Success sending message."); return(InvokeResult.Success); } else { ReceivedContent = $"{responseMessage.StatusCode} - {responseMessage.ReasonPhrase}"; await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending message: {ReceivedContent}."); return(InvokeResult.FromError(ReceivedContent)); } } }
private static Expression ParseExpressionShift(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // exprBitAnd ::= exprCmp { ( << | >> ) exprCmp } var expr = ParseExpressionPlus(scope, code, result, ref lWrap); while (true) { LuaToken tokenTyp = code.Current.Typ; ExpressionType exprTyp; if (tokenTyp == LuaToken.ShiftLeft) exprTyp = ExpressionType.LeftShift; else if (tokenTyp == LuaToken.ShiftRight) exprTyp = ExpressionType.RightShift; else return expr; code.Next(); expr = BinaryOperationExpression(scope.Runtime, code.Current, exprTyp, expr, ParseExpressionPlus(scope, code, InvokeResult.Object, ref lWrap)); lWrap |= true; } }
public async Task <InvokeResult <AuthResponse> > CreateUserAsync(RegisterUser newUser, bool sendAuthEmail = true, bool autoLogin = true) { if (String.IsNullOrEmpty(newUser.Email)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingEmail.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingEmail.ToErrorMessage())); } var user = await _appUserRepo.FindByEmailAsync(newUser.Email); if (user != null) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegErrorUserExists.Message); if (sendAuthEmail) { return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegErrorUserExists.ToErrorMessage())); } else { return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegisterUserExists_3rdParty.ToErrorMessage())); } } /* Need to check all these, if any fail, we want to aboart, we need to refactor this into the UserAdmin module :( */ if (String.IsNullOrEmpty(newUser.AppId)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingAppId.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingAppId.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.ClientType)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingClientType.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingClientType.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.DeviceId)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingDeviceId.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingDeviceId.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.FirstName)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingFirstLastName.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingFirstLastName.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.LastName)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingLastName.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingLastName.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.Password)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingPassword.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingPassword.ToErrorMessage())); } var emailRegEx = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); if (!emailRegEx.Match(newUser.Email).Success) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegInvalidEmailAddress.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegInvalidEmailAddress.ToErrorMessage())); } var appUser = new AppUser(newUser.Email, $"{newUser.FirstName} {newUser.LastName}") { FirstName = newUser.FirstName, LastName = newUser.LastName, }; var identityResult = await _userManager.CreateAsync(appUser, newUser.Password); if (identityResult.Successful) { await LogEntityActionAsync(appUser.Id, typeof(AppUser).Name, "New User Registered", null, appUser.ToEntityHeader()); if (autoLogin) { await _signInManager.SignInAsync(appUser); } if (newUser.ClientType != "WEBAPP") { var authRequest = new AuthRequest() { AppId = newUser.AppId, DeviceId = newUser.DeviceId, AppInstanceId = newUser.AppInstanceId, ClientType = newUser.ClientType, GrantType = "password", Email = newUser.Email, UserName = newUser.Email, Password = newUser.Password, }; var tokenResponse = await _authTokenManager.AccessTokenGrantAsync(authRequest); if (tokenResponse.Successful) { await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader()); return(InvokeResult <AuthResponse> .Create(tokenResponse.Result)); } else { var failedValidationResult = new InvokeResult <AuthResponse>(); failedValidationResult.Concat(tokenResponse); return(failedValidationResult); } } else { if (sendAuthEmail) { await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader()); } /* If we are logging in as web app, none of this applies */ return(InvokeResult <AuthResponse> .Create(new AuthResponse() { AccessToken = "N/A", AccessTokenExpiresUTC = "N/A", RefreshToken = "N/A", AppInstanceId = "N/A", RefreshTokenExpiresUTC = "N/A", IsLockedOut = false, User = appUser.ToEntityHeader(), Roles = new List <EntityHeader>() })); } } else { return(InvokeResult <AuthResponse> .FromInvokeResult(identityResult)); } }
private static Expression ParseExpressionBitXOr(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // exprBitXOr ::= exprBitAnd { ~ exprBitAnd } var expr = ParseExpressionBitAnd(scope, code, result, ref lWrap); while (code.Current.Typ == LuaToken.Dilde) { code.Next(); expr = BinaryOperationExpression(scope.Runtime, code.Current, ExpressionType.ExclusiveOr, expr, ParseExpressionBitAnd(scope, code, InvokeResult.Object, ref lWrap) ); lWrap |= true; } return expr; }
private static Expression ParseExpressionMultiply(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // expMul ::= expUn { ( * | / | // | % ) expUn } var expr = ParseExpressionUnary(scope, code, result, ref lWrap); while (true) { LuaToken tokenTyp = code.Current.Typ; ExpressionType exprTyp; if (tokenTyp == LuaToken.Star) exprTyp = ExpressionType.Multiply; else if (tokenTyp == LuaToken.Slash) exprTyp = ExpressionType.Divide; else if (tokenTyp == LuaToken.SlashShlash) exprTyp = Lua.IntegerDivide; else if (tokenTyp == LuaToken.Percent) exprTyp = ExpressionType.Modulo; else return expr; code.Next(); expr = BinaryOperationExpression(scope.Runtime, code.Current, exprTyp, expr, ParseExpressionUnary(scope, code, InvokeResult.Object, ref lWrap)); lWrap |= true; } }
public override InvokeResult Execute(string config, DateTime runDateTime, InvokeResult previousStepResult) { Console.WriteLine("五心内天开始执行"); base.LogWrite("五心内天开始执行"); return(ConfigHelper.GetBoolTrueValue("IsRunSucess") ? base.CreateSuccessResult() : base.CreateFailResult()); }
public Expression GenerateGet(Scope scope, InvokeResult result) { if (Instance != null && Member == null && Indices != null && Arguments == null) { if (Indices.Length > 0) { // First the arguments are pushed on the stack, and later comes the call, so we wrap the last parameter Indices[Indices.Length - 1] = WrapDebugInfo(scope.EmitExpressionDebug, true, Position, Position, Indices[Indices.Length - 1]); // Let the type as it is } Instance = IndexGetExpression(scope, Position, Instance, Indices); Indices = null; } else if (Instance != null && Member != null && Indices == null && Arguments == null) { // Convert the member to an instance Instance = WrapDebugInfo(scope.EmitExpressionDebug, true, Position, Position, Instance); Instance = MemberGetExpression(scope, Position, Instance, Member); Member = null; MethodMember = false; } else if (Instance != null && Member == null && Indices == null && Arguments == null) { // Nothing to todo, we have already an instance } else if (Instance != null && Indices == null && Arguments != null) { if (Arguments.Count > 0) { // First the arguments are pushed on the stack, and later comes the call, so we wrap the last parameter Arguments.WrapArgument(Arguments.Count - 1, scope.EmitExpressionDebug, Position); // Let the type as it is } else Instance = WrapDebugInfo(scope.EmitExpressionDebug, true, Position, Position, Instance); if (String.IsNullOrEmpty(Member)) Instance = InvokeExpression(scope, Position, Instance, result, Arguments, true); else Instance = InvokeMemberExpression(scope, Position, Instance, Member, result, Arguments); Member = null; MethodMember = false; Arguments = null; } else throw ParseError(Position, Properties.Resources.rsParseExpressionNoResult); return Instance; }
public void Init() { _secureStorage.Setup <Task <InvokeResult <string> > >(srs => srs.AddSecretAsync(_org, It.IsAny <string>())).ReturnsAsync(InvokeResult <string> .Create("passingid")); _deviceMgmtSettings.Setup <IConnectionSettings>(dms => dms.DefaultDeviceTableStorage).Returns(_defaultTableStorageSettings); _deviceMgmtSettings.Setup <IConnectionSettings>(dms => dms.DefaultDeviceStorage).Returns(_deviceStorageSettings); _defaultTSJson = JsonConvert.SerializeObject(_defaultTableStorageSettings); _defaultDeviceStorageJson = JsonConvert.SerializeObject(_deviceStorageSettings); }
public async Task <InvokeResult <Uri> > AddFileAsync(string fileName, byte[] data, string contentType = "application/octet-stream") { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException(nameof(fileName)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } var result = await GetStorageContainerAsync(_containerName); if (!result.Successful) { return(InvokeResult <Uri> .FromInvokeResult(result.ToInvokeResult())); } var container = result.Result; if (fileName.StartsWith("/")) { fileName = fileName.TrimStart('/'); } var blob = container.GetBlockBlobReference(fileName); blob.Properties.ContentType = contentType; //TODO: Should really encapsulate the idea of retry of an action w/ error reporting var numberRetries = 5; var retryCount = 0; var completed = false; var stream = new MemoryStream(data); while (retryCount++ < numberRetries && !completed) { try { stream.Seek(0, SeekOrigin.Begin); await blob.UploadFromStreamAsync(stream); } catch (Exception ex) { if (retryCount == numberRetries) { _logger.AddException("CloudFileStorage_AddFileAsync", ex, _containerName.ToKVP("containerName")); var exceptionResult = InvokeResult.FromException("CloudFileStorage_AddFileAsync", ex); return(InvokeResult <Uri> .FromInvokeResult(exceptionResult)); } else { _logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Warning, "CloudFileStorage_AddFileAsync", "", ex.Message.ToKVP("exceptionMessage"), ex.GetType().Name.ToKVP("exceptionType"), retryCount.ToString().ToKVP("retryCount")); } await Task.Delay(retryCount * 250); } } return(InvokeResult <Uri> .Create(blob.Uri)); }
public InvokeResult <string> ToPEM() { if (!String.IsNullOrEmpty(JSON)) { var pem = JsonConvert.DeserializeObject(JSON) as JObject; if (pem == null) { return(InvokeResult <string> .FromError("Could not deserialize PEM JSON")); } pem.Add("textPayload", TextPayload); var envelope = pem["envelope"] as JObject; if (envelope == null) { return(InvokeResult <string> .FromError("Could not deserialize PEM Envelope")); } if (!String.IsNullOrEmpty(Values)) { var values = JsonConvert.DeserializeObject(Values) as JObject; if (values != null) { envelope.Add("values", values); } } if (!String.IsNullOrEmpty(Log)) { var log = JsonConvert.DeserializeObject(Log) as JArray; if (log != null) { if (pem.ContainsKey("log")) { pem.Remove("log"); } pem.Add("log", Log); } } if (!string.IsNullOrEmpty(Device)) { var device = JsonConvert.DeserializeObject(Device) as JObject; if (device != null) { if (pem.ContainsKey("device")) { pem.Remove("device"); } pem.Add("device", device); } } if (!string.IsNullOrEmpty(Instructions)) { var instructions = JsonConvert.DeserializeObject(Instructions) as JArray; if (instructions != null) { if (pem.ContainsKey("instructions")) { pem.Remove("instructions"); } pem.Add("instructions", instructions); } } if (!string.IsNullOrEmpty(ResponseMessage)) { var responseMessage = JsonConvert.DeserializeObject(ResponseMessage) as JObject; if (responseMessage != null) { if (pem.ContainsKey("responseMessage")) { pem.Remove("responseMessage"); } pem.Add("responseMessage", responseMessage); } } if (!string.IsNullOrEmpty(OutgoingMessages)) { var outgoingMessages = JsonConvert.DeserializeObject(OutgoingMessages) as JArray; if (outgoingMessages != null) { if (pem.ContainsKey("outgoingMessages")) { pem.Remove("outgoingMessages"); } pem.Add("outgoingMessages", outgoingMessages); } } return(InvokeResult <string> .Create(pem.ToString())); } return(InvokeResult <string> .FromError("JSON In Table Storage Entity was null or empty")); }
/// <summary> /// 对需要更新的队列数据更新操作进行批量处理,可考虑异步执行 /// </summary> public static void StartDbChangeProcessQuick(MongoOperation mongoDbOp, bool isDefaultField = false) { if (mongoDbOp == null) { var connStr = "mongodb://*****:*****@192.168.1.230:37088/SimpleCrawler"; mongoDbOp = new MongoOperation(connStr); } var result = new InvokeResult(); List <StorageData> updateList = new List <StorageData>(); while (DBChangeQueue.Instance.Count > 0) { var temp = DBChangeQueue.Instance.DeQueue(); if (temp != null) { var insertDoc = temp.Document; switch (temp.Type) { case StorageType.Insert: if (isDefaultField == true) { if (insertDoc.Contains("createDate") == false) { insertDoc.Add("createDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //添加时,默认增加创建时间 } if (insertDoc.Contains("createUserId") == false) { insertDoc.Add("createUserId", "1"); } //更新用户 if (insertDoc.Contains("underTable") == false) { insertDoc.Add("underTable", temp.Name); } insertDoc.Set("updateDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //更新时间 insertDoc.Set("updateUserId", "1"); } result = mongoDbOp.Save(temp.Name, insertDoc);; break; case StorageType.Update: result = mongoDbOp.Save(temp.Name, temp.Query, insertDoc); break; case StorageType.Delete: result = mongoDbOp.Delete(temp.Name, temp.Query); break; } //logInfo1.Info(""); if (result.Status == Status.Failed) { //throw new Exception(result.Message); } } } if (DBChangeQueue.Instance.Count > 0) { StartDbChangeProcessQuick(mongoDbOp, isDefaultField); } }
public async Task <InvokeResult> InvokeAsync(InvokeOptions options) { using (var form = _formFactory.Invoke()) using (var browser = new ExtendedWebBrowser() { Dock = DockStyle.Fill }) { var signal = new SemaphoreSlim(0, 1); var result = new InvokeResult { ResultType = InvokeResultType.UserCancel }; form.FormClosed += (o, e) => { signal.Release(); }; browser.NavigateError += (o, e) => { e.Cancel = true; result.ResultType = InvokeResultType.HttpError; result.Error = e.StatusCode.ToString(); signal.Release(); }; browser.BeforeNavigate2 += (o, e) => { if (e.Url.StartsWith(options.EndUrl)) { e.Cancel = true; result.ResultType = InvokeResultType.Success; if (options.ResponseMode == ResponseMode.FormPost) { result.Response = Encoding.UTF8.GetString(e.PostData ?? new byte[] { }); } else { result.Response = e.Url; } signal.Release(); } }; form.Controls.Add(browser); browser.Show(); System.Threading.Timer timer = null; if (options.InitialDisplayMode != DisplayMode.Visible) { result.ResultType = InvokeResultType.Timeout; timer = new System.Threading.Timer((o) => { var args = new HiddenModeFailedEventArgs(result); HiddenModeFailed?.Invoke(this, args); if (args.Cancel) { browser.Stop(); form.Invoke(new Action(() => form.Close())); } else { form.Invoke(new Action(() => form.Show())); } }, null, (int)options.InvisibleModeTimeout.TotalSeconds * 1000, Timeout.Infinite); } else { form.Show(); } browser.Navigate(options.StartUrl); await signal.WaitAsync(); if (timer != null) { timer.Change(Timeout.Infinite, Timeout.Infinite); } form.Hide(); browser.Hide(); return(result); } }
private static Expression InvokeExpression(Scope scope, Token tStart, Expression instance, InvokeResult result, Expression[] arguments, bool lParse) { MethodInfo mi; ConstantExpression constInstance = instance as ConstantExpression; LuaType t; if (constInstance != null && (t = constInstance.Value as LuaType) != null && t.Type != null) // we have a type, bind the ctor { Type type = t.Type; TypeInfo typeInfo = type.GetTypeInfo(); ConstructorInfo ci = typeInfo.IsValueType && arguments.Length == 0 ? null : LuaEmit.FindMember(typeInfo.DeclaredConstructors.Where(c => c.IsPublic), arguments, getExpressionTypeFunction); if (ci == null && !typeInfo.IsValueType) throw ParseError(tStart, String.Format(Properties.Resources.rsMemberNotResolved, type.Name, "ctor")); return SafeExpression(() => LuaEmit.BindParameter(scope.Runtime, args => ci == null ? Expression.New(type) : Expression.New(ci, args), ci == null ? new ParameterInfo[0] : ci.GetParameters(), arguments, getExpressionFunction, getExpressionTypeFunction, true), tStart); } else if (LuaEmit.IsDynamicType(instance.Type)) { // fallback is a dynamic call return EnsureInvokeResult(scope, tStart, DynamicExpression.Dynamic(scope.Runtime.GetInvokeBinder(new CallInfo(arguments.Length)), typeof(object), new Expression[] { ConvertExpression(scope.Runtime, tStart, instance, typeof(object)) }.Concat( from c in arguments select Lua.EnsureType(c, typeof(object)) ) ), result, instance, null ); } else if (typeof(Delegate).GetTypeInfo().IsAssignableFrom(instance.Type.GetTypeInfo()) && // test if the type is assignable from delegate (mi = instance.Type.GetRuntimeMethods().Where(c => !c.IsStatic && c.IsPublic && c.Name == "Invoke").FirstOrDefault()) != null) // Search the Invoke method for the arguments { return EnsureInvokeResult(scope, tStart, SafeExpression(() => LuaEmit.BindParameter<Expression>( scope.Runtime, args => Expression.Invoke(instance, args), mi.GetParameters(), arguments, getExpressionFunction, getExpressionTypeFunction, true), tStart), result, instance, null ); } else throw ParseError(tStart, LuaEmitException.GetMessageText(LuaEmitException.InvokeNoDelegate, instance.Type.Name)); }
/// <summary> /// 解析项目列表页面 /// </summary> /// <param name="productType"></param> /// <param name="htmlString"></param> /// <returns></returns> private InvokeResult ParseProjectList_New(string cityGuid, string productType, string htmlString) { InvokeResult result = new InvokeResult() { Status = Status.Failed }; HtmlDocument document = new HtmlDocument(); document.LoadHtml(htmlString); HtmlNode rootNode = document.DocumentNode; HtmlNodeCollection nodes = rootNode.SelectNodes("//div[@class='s-lp-all ']"); List <BsonDocument> projectDocs = new List <BsonDocument>(); bool isSuccessful = true; if (nodes != null) { foreach (var node in nodes) { try { BsonDocument doc = new BsonDocument(); HtmlNode tempNode = node.SelectSingleNode("div[@class='list']/div[@class='txt-center']/div[@class='title']"); HtmlNode tn = null; #region 获取项目名称、业态、销售状态 if (tempNode != null) { #region 项目名及链接 tn = tempNode.SelectSingleNode("a"); if (tn != null) { doc.Add("name", tn.InnerText.Trim()); if (tn.Attributes.Contains("href") == true) { string detailUrl = tn.Attributes["href"].Value.Trim(); doc.Add("detailUrl", detailUrl); #region 解析项目ID string[] tempArr = detailUrl.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); string fileName = tempArr[tempArr.Length - 1]; doc.Add("projId", fileName.Replace(".html", "")); #endregion } } #endregion #region 销售状态 tn = tempNode.SelectSingleNode("span"); if (tn != null) { doc.Add("saleStatus", tn.InnerText.Trim()); } #endregion #region 项目业态 tn = tempNode.SelectSingleNode("em"); if (tn != null) { string tmpString = tn.InnerText.Replace("[", "").Replace("]", "").Trim(); string[] arrProductType = (from m in tmpString.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries) select m.Trim()).ToArray(); doc.Add("productType", string.Join(",", arrProductType)); } #endregion } #endregion #region 获取项目地址和所在区 tempNode = node.SelectSingleNode("div[@class='list']/div[@class='txt-center']/p[@class='location']"); if (tempNode != null) { #region 项目地址和所在区 tn = tempNode.SelectSingleNode("span"); if (tn != null) { doc.Add("address", tn.InnerText.Trim()); string[] arr = tn.InnerText.Trim().Trim().Split(new string[] { " ", " " }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length > 0) { doc.Add("region", arr[0]); //是否匹配显示 var hitRegion = curCityRegionList.Where(c => c.Text("name").Contains(arr[0])).Count() > 0; if (hitRegion == false && curCityRegionList.Count() > 1) { Console.WriteLine("{0}不是{1}的县市", arr[0], cityGuid); continue; } } } #endregion #region 地图经纬度 tn = tempNode.SelectSingleNode("a"); if (tn != null) { if (tn.Attributes.Contains("data-lon") == true) { doc.Add("x", tn.Attributes["data-lon"].Value.Trim()); } if (tn.Attributes.Contains("data-lat") == true) { doc.Add("y", tn.Attributes["data-lat"].Value.Trim()); } } #endregion } #endregion if (doc.Elements.Count() > 0) { //厦门站包含泉州漳州楼盘 var xmDistionct = new string[] { "思明", "翔安", "湖里", "同安", "海沧", "集美" }; if (cityGuid == "XM-44FBDA82-53FB-4206-B209-2B394B54F1FF" && !xmDistionct.Contains(doc.Text("region"))) { continue; } doc.Add("cityGuid", cityGuid); doc.Add("dataSource", "focus"); doc.Add("isNeedUpdate", "1");//需要爬取详细信息 projectDocs.Add(doc); } else { Console.WriteLine("无获取到任何数据"); } } catch (Exception ex) { isSuccessful = false; Console.WriteLine("解析起始页出现异常:" + ex.Message); } } } if (projectDocs.Count() > 0) { Console.WriteLine("获取项目:" + projectDocs.Count().ToString() + " 并开始保存到数据库中"); this.SaveProject(projectDocs); } result.Status = isSuccessful == true ? Status.Successful : Status.Failed; return(result); }
private static Expression InvokeMemberExpressionDynamic(Scope scope, Token tStart, Expression instance, string sMember, InvokeResult result, Expression[] arguments) { return EnsureInvokeResult(scope, tStart, DynamicExpression.Dynamic(scope.Runtime.GetInvokeMemberBinder(sMember, new CallInfo(arguments.Length)), typeof(object), new Expression[] { ConvertExpression(scope.Runtime, tStart, instance, typeof(object)) }.Concat(from a in arguments select Lua.EnsureType(a, typeof(object))).ToArray() ), result, instance, sMember ); }
/// <summary> /// 解析项目列表页面 /// </summary> /// <returns></returns> private InvokeResult ParseProjectList(string cityGuid, string productType, string htmlString) { InvokeResult result = new InvokeResult() { Status = Status.Failed }; HtmlDocument document = new HtmlDocument(); document.LoadHtml(htmlString); HtmlNode rootNode = document.DocumentNode; HtmlNode node = rootNode.SelectSingleNode("//div[@class='s-lp-list']"); List <BsonDocument> projectDocs = new List <BsonDocument>(); bool isSuccessful = true; if (node != null) { HtmlNodeCollection childNodes = node.SelectNodes("div[@class='lp-list-li _item_li']"); if (childNodes == null) { return(result); } foreach (var child in childNodes) { try { BsonDocument doc = new BsonDocument(); HtmlNode tempNode = null; if (child.Attributes.Contains("projId") == true) { doc.Add("projId_key", child.Attributes["projId"].Value.Trim()); } if (child.Attributes.Contains("groupId") == true) { doc.Add("groupId_key", child.Attributes["groupId"].Value.Trim()); doc.Add("projId", child.Attributes["groupId"].Value.Trim()); } #region 项目名称、项目详情URL tempNode = child.SelectSingleNode("div/div/div[@class='s-lp-txt-center']/div/a"); if (tempNode != null) { doc.Add("name", tempNode.InnerText.Trim()); if (tempNode.Attributes.Contains("href") == true) { doc.Add("detailUrl", tempNode.Attributes["href"].Value.Trim()); } } #endregion #region 项目销售状态 tempNode = child.SelectSingleNode("div/div/div[@class='s-lp-txt-center']/div/span[@class='lp-state zs']"); if (tempNode != null) { doc.Add("saleStatus", tempNode.InnerText.Trim()); } #endregion #region 项目业态 tempNode = child.SelectSingleNode("div/div/div[@class='s-lp-txt-center']/div/em[@class='lp-type']"); if (tempNode != null) { string tmpString = tempNode.InnerText.Replace("[", "").Replace("]", "").Trim(); string[] arrProductType = (from m in tmpString.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries) select m.Trim()).ToArray(); doc.Add("productType", string.Join(",", arrProductType)); } #endregion #region 获取项目地址和所在区 tempNode = child.SelectSingleNode("div/div/div[@class='s-lp-txt-center']/p[1]/span"); if (tempNode != null) { if (tempNode.Attributes.Contains("title") == true) { doc.Add("address", tempNode.Attributes["title"].Value.Trim()); string[] arr = tempNode.Attributes["title"].Value.Trim().Split(new string[] { " ", " " }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length > 0) { doc.Add("region", arr[0]); } } } #endregion if (doc.Elements.Count() > 0) { doc.Add("cityGuid", cityGuid); doc.Add("dataSource", "focus"); projectDocs.Add(doc); } } catch (Exception ex) { isSuccessful = false; Console.WriteLine("解析起始页出现异常:" + ex.Message); } } } if (projectDocs.Count() > 0) { Console.WriteLine("获取项目:" + projectDocs.Count().ToString() + " 并开始保存到数据库中"); this.SaveProject(projectDocs); } result.Status = isSuccessful == true ? Status.Successful : Status.Failed; return(result); }
private static Expression ParseExpression(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // expr ::= exprOr return ParseExpressionOr(scope, code, result, ref lWrap); }
public virtual void Process(HttpContext context, InvokeResult checkPowerResult) { }
private static Expression ParseExpressionCmp(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // expCmd ::= expCon { ( < | > | <= | >= | ~= | == ) expCon } Token tStart = code.Current; var expr = ParseExpressionCon(scope, code, result, ref lWrap); while (true) { LuaToken tokenTyp = code.Current.Typ; ExpressionType exprTyp; if (tokenTyp == LuaToken.Lower) exprTyp = ExpressionType.LessThan; else if (tokenTyp == LuaToken.Greater) exprTyp = ExpressionType.GreaterThan; else if (tokenTyp == LuaToken.LowerEqual) exprTyp = ExpressionType.LessThanOrEqual; else if (tokenTyp == LuaToken.GreaterEqual) exprTyp = ExpressionType.GreaterThanOrEqual; else if (tokenTyp == LuaToken.NotEqual) exprTyp = ExpressionType.NotEqual; else if (tokenTyp == LuaToken.Equal) exprTyp = ExpressionType.Equal; else return expr; code.Next(); expr = BinaryOperationExpression(scope.Runtime, code.Current, exprTyp, expr, ParseExpressionCon(scope, code, InvokeResult.Object, ref lWrap)); lWrap |= true; } }
public InvokeResult CreateAll(IList <WorkPlan> workPlans) { InvokeResult result = new InvokeResult { Success = true }; try { List <IBatisNetBatchStatement> statements = new List <IBatisNetBatchStatement>(); string oldManId = ""; string roomId = ""; List <string> arroldManIds = new List <string>(); foreach (WorkPlan workPlan in workPlans) { if (workPlan.PlanId == GlobalManager.GuidAsAutoGenerate) { workPlan.PlanId = Guid.NewGuid(); } /***********************begin 自定义代码*******************/ workPlan.OperatedBy = NormalSession.UserId.ToGuid(); workPlan.OperatedOn = DateTime.Now; if (oldManId != workPlan.OldManId.ToString()) { string sql = "select RoomId from Pam_RoomOldMan where OldManId='" + workPlan.OldManId.ToString() + "' and EndDate>GETDATE()"; var ret = BuilderFactory.DefaultBulder().ExecuteNativeSqlForQuery(sql); if (ret.Count == 1) { roomId = ret[0]["RoomId"].ToString(); oldManId = workPlan.OldManId.ToString(); arroldManIds.Add(workPlan.OldManId.ToString()); } else { result.Success = false; result.ErrorMessage = "老人所在的房间出现异常"; return(result); } } workPlan.RoomId = roomId.ToGuid(); /***********************end 自定义代码*********************/ statements.Add(new IBatisNetBatchStatement { StatementName = workPlan.GetCreateMethodName(), ParameterObject = workPlan.ToStringObjectDictionary(false), Type = SqlExecuteType.INSERT }); /***********************begin 自定义代码*******************/ /***********************此处添加自定义代码*****************/ /***********************end 自定义代码*********************/ } if (statements.Count > 0) { BuilderFactory.DefaultBulder().ExecuteNativeSqlNoneQuery(statements); foreach (string arroldManId in arroldManIds) { SPParam spParam = new { }.ToSPParam(); spParam["OldManId"] = arroldManId.ToGuid(); spParam["BatchFlag"] = 0; BuilderFactory.DefaultBulder().ExecuteSPNoneQuery("SP_Pam_GenDailyWorkExcute", spParam); } } } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.Message; } return(result); }
private static Expression ParseExpressionPlus(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // expPlus ::= expMul { ( + | - ) expMul} var expr = ParseExpressionMultiply(scope, code, result, ref lWrap); while (true) { LuaToken tokenTyp = code.Current.Typ; ExpressionType exprTyp; if (tokenTyp == LuaToken.Plus) exprTyp = ExpressionType.Add; else if (tokenTyp == LuaToken.Minus) exprTyp = ExpressionType.Subtract; else return expr; code.Next(); expr = BinaryOperationExpression(scope.Runtime, code.Current, exprTyp, expr, ParseExpressionMultiply(scope, code, InvokeResult.Object, ref lWrap)); lWrap |= true; } }
} // func IndexSetExpression private static Expression InvokeExpression(Scope scope, Token tStart, Expression instance, InvokeResult result, ArgumentsList arguments, bool lParse) { MethodInfo mi; ConstantExpression constInstance = instance as ConstantExpression; LuaType t; if (constInstance != null && (t = constInstance.Value as LuaType) != null && t.Type != null) // we have a type, bind the ctor { var type = t.Type; var typeInfo = type.GetTypeInfo(); var ci = typeInfo.IsValueType && arguments.Count == 0 ? null : LuaEmit.FindMember(typeInfo.DeclaredConstructors.Where(c => c.IsPublic), arguments.CallInfo, arguments.Expressions, getExpressionTypeFunction, false); if (ci == null && !typeInfo.IsValueType) { throw ParseError(tStart, String.Format(Properties.Resources.rsMemberNotResolved, type.Name, "ctor")); } return(SafeExpression(() => LuaEmit.BindParameter(scope.Runtime, args => ci == null ? Expression.New(type) : Expression.New(ci, args), ci == null ? new ParameterInfo[0] : ci.GetParameters(), arguments.CallInfo, arguments.Expressions, getExpressionFunction, getExpressionTypeFunction, true), tStart)); } else if (LuaEmit.IsDynamicType(instance.Type)) { // fallback is a dynamic call return(EnsureInvokeResult(scope, tStart, DynamicExpression.Dynamic(scope.Runtime.GetInvokeBinder(arguments.CallInfo), typeof(object), new Expression[] { ConvertExpression(scope.Runtime, tStart, instance, typeof(object)) }.Concat( from c in arguments.Expressions select Lua.EnsureType(c, typeof(object)) ) ), result, instance, null )); } else if (typeof(Delegate).GetTypeInfo().IsAssignableFrom(instance.Type.GetTypeInfo()) && // test if the type is assignable from delegate (mi = instance.Type.GetRuntimeMethods().Where(c => !c.IsStatic && c.IsPublic && c.Name == "Invoke").FirstOrDefault()) != null) // Search the Invoke method for the arguments { return(EnsureInvokeResult(scope, tStart, SafeExpression(() => LuaEmit.BindParameter <Expression>( scope.Runtime, args => Expression.Invoke(instance, args), mi.GetParameters(), arguments.CallInfo, arguments.Expressions, getExpressionFunction, getExpressionTypeFunction, true), tStart), result, instance, null )); } else { throw ParseError(tStart, LuaEmitException.GetMessageText(LuaEmitException.InvokeNoDelegate, instance.Type.Name)); } } // func InvokeExpression
/// <summary> /// 组织架构同步 /// </summary> /// <param name="node"></param> /// <param name="pnode"></param> /// <returns></returns> public List <ADDepartment> OrgTreeInsert(ADDepartment node, ADDepartment pnode) { InvokeResult result = new InvokeResult(); List <ADDepartment> nodeList = new List <ADDepartment>(); ADDepartment retNode = new ADDepartment(); ADDepartment subnode = new ADDepartment(); try { subnode = node; retNode.Name = subnode.Name; retNode.Level = subnode.Level; int pid = 0; if (pnode == null) { pid = 0; } else { pid = pnode.DepId; } var org = _dataOp.FindAll("Organization").Where(t => t.Text("guid") == subnode.Guid).FirstOrDefault(); BsonDocument structModel = new BsonDocument(); structModel.Add("name", subnode.Name); structModel.Add("nodePid", pid.ToString()); structModel.Add("guid", subnode.Guid); structModel.Add("state", "0"); structModel.Add("code", subnode.Code); Console.WriteLine("组织架构:{0}——>{1}", structModel.Text("name"), structModel.Text("guid")); if (org == null) { result = _dataOp.Insert("Organization", structModel); } else { result = _dataOp.Update("Organization", "db.Organization.distinct('_id',{'guid':'" + subnode.Guid + "'})", structModel); } if (result.Status == Status.Successful) { var orgpost = _dataOp.FindAllByKeyVal("OrgPost", "orgId", result.BsonInfo.Text("orgId")); if (orgpost.Count() == 0) { BsonDocument post = new BsonDocument(); post.Add("name", "空缺岗位"); post.Add("orgId", result.BsonInfo.Text("orgId")); post.Add("type", "0"); _dataOp.Insert("OrgPost", post); } subnode.DepId = result.BsonInfo.Int("orgId"); retNode.DepId = subnode.DepId; } nodeList.Add(retNode); // Console.WriteLine(string.Format("Level:{0} Name:{1}", subnode.Level, subnode.Name)); if (subnode.SubDepartemnt != null) { foreach (var item in subnode.SubDepartemnt) { nodeList.AddRange(OrgTreeInsert(item, subnode)); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(nodeList); }
} // func InvokeExpression private static Expression InvokeMemberExpression(Scope scope, Token tStart, Expression instance, string memberName, InvokeResult result, ArgumentsList arguments) { if (LuaEmit.IsDynamicType(instance.Type) || arguments.Expressions.Any(c => LuaEmit.IsDynamicType(c.Type))) { var dynamicArguments = new Expression[arguments.Count + 1]; // first argument is the instance dynamicArguments[0] = ConvertObjectExpression(scope.Runtime, tStart, instance, false); if (arguments.Count > 0) { // single object for (var i = 0; i < arguments.Count - 1; i++) { dynamicArguments[i + 1] = ConvertObjectExpression(scope.Runtime, tStart, arguments.Expressions[i], false); } // last argument is different if (arguments.CallInfo.ArgumentNames.Count > 0) { dynamicArguments[dynamicArguments.Length - 1] = ConvertObjectExpression(scope.Runtime, tStart, arguments.Expressions[arguments.Count - 1], false); } else { dynamicArguments[dynamicArguments.Length - 1] = Lua.EnsureType(arguments.Expressions[arguments.Count - 1], typeof(object)); } } return(EnsureInvokeResult(scope, tStart, DynamicExpression.Dynamic(scope.Runtime.GetInvokeMemberBinder(memberName, arguments.CallInfo), typeof(object), dynamicArguments), result, instance, memberName )); } else { return(EnsureInvokeResult(scope, tStart, SafeExpression(() => { Expression expr; if (!LuaEmit.TryInvokeMember <Expression>(scope.Runtime, LuaType.GetType(instance.Type), instance, arguments.CallInfo, arguments.Expressions, memberName, false, e => e, e => e.Type, true, out expr)) { throw new LuaEmitException(LuaEmitException.MemberNotFound, instance.Type, memberName); } return expr; }, tStart), result, instance, memberName )); } } // func InvokeMemberExpression
public async Task <InvokeResult> ConnectAsync() { try { IsBusy = true; switch (_simulator.DefaultTransport.Value) { /* case TransportTypes.AMQP: * { * var connectionString = $"Endpoint=sb://{Model.DefaultEndPoint}.servicebus.windows.net/;SharedAccessKeyName={Model.AccessKeyName};SharedAccessKey={Model.AccessKey}"; * var bldr = new EventHubsConnectionStringBuilder(connectionString) * { * EntityPath = Model.HubName * }; * * _isConnected = true; * } * * break;*/ case TransportTypes.AzureIoTHub: await ConnectAzureIoTHubAsync(); break; case TransportTypes.MQTT: await MQTTConnectAsync(); break; case TransportTypes.TCP: await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Connecting to {_simulator.DefaultTransport.Text} - {_simulator.DefaultEndPoint} on {_simulator.DefaultPort}."); _tcpClient = _runtimeService.GetTCPClient(); await _tcpClient.ConnectAsync(_simulator.DefaultEndPoint, _simulator.DefaultPort); StartReceiveThread(); SetConnectedState(); await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Connected to {_simulator.DefaultTransport.Text} - {_simulator.DefaultEndPoint} on {_simulator.DefaultPort}."); break; case TransportTypes.UDP: await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Connecting to {_simulator.DefaultTransport.Text} - {_simulator.DefaultEndPoint} on {_simulator.DefaultPort}."); _udpClient = _runtimeService.GetUDPCLient(); await _udpClient.ConnectAsync(_simulator.DefaultEndPoint, _simulator.DefaultPort); StartReceiveThread(); SetConnectedState(); await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Connected to {_simulator.DefaultTransport.Text} - {_simulator.DefaultEndPoint} on {_simulator.DefaultPort}."); break; case TransportTypes.RestHttp: case TransportTypes.RestHttps: break; default: await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Attempt to connect to {_simulator.DefaultTransport.Text} that does not allow connections.."); break; } return(InvokeResult.Success); } catch (Exception ex) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error connecting to {_simulator.DefaultTransport.Text} - {ex.Message}."); if (_mqttClient != null) { _mqttClient.Dispose(); _mqttClient = null; } if (_azureIoTHubClient != null) { await _azureIoTHubClient.CloseAsync(); _azureIoTHubClient.Dispose(); _azureIoTHubClient = null; } if (_tcpClient != null) { await _tcpClient.DisconnectAsync(); _tcpClient.Dispose(); _tcpClient = null; } if (_udpClient != null) { await _udpClient.DisconnectAsync(); _udpClient.Dispose(); _udpClient = null; } SetDisconnectedState(); return(InvokeResult.FromException("ConnectAsync", ex)); } finally { IsBusy = false; } }
} // func InvokeMemberExpression private static Expression EnsureInvokeResult(Scope scope, Token tStart, Expression expr, InvokeResult result, Expression instance, string memberName) { switch (result) { case InvokeResult.LuaResult: if (expr.Type == typeof(object)) { return(ConvertExpression(scope.Runtime, tStart, expr, typeof(LuaResult))); } else { return(MemberGetSandbox(scope, expr, instance, memberName)); } case InvokeResult.Object: if (LuaEmit.IsDynamicType(expr.Type)) { return(MemberGetSandbox(scope, DynamicExpression.Dynamic(scope.Runtime.GetConvertBinder(typeof(object)), typeof(object), ConvertExpression(scope.Runtime, tStart, expr, typeof(object))), instance, memberName)); } else { return(MemberGetSandbox(scope, expr, instance, memberName)); } default: return(MemberGetSandbox(scope, expr, instance, memberName)); } } // func EnsureInvokeResult
private async Task <InvokeResult> SendHTMLGeoMessage(MessageTransmissionPlan plan) { var messageTemplate = plan.Message.Value; var pointArray = messageTemplate.TextPayload.Split('\r'); var geoLocation = pointArray[_pointIndex++]; var parts = geoLocation.Split(','); var lat = Convert.ToDouble(parts[0]); var lon = Convert.ToDouble(parts[1]); var delay = Convert.ToInt32(parts[2]) * 1000; using (var client = new HttpClient()) { var protocol = messageTemplate.Transport.Value == TransportTypes.RestHttps ? "https" : "http"; var uri = $"{protocol}://{_simulator.DefaultEndPoint}:{_simulator.DefaultPort}{ReplaceTokens(_instance, plan, messageTemplate.PathAndQueryString)}"; if (!this._simulator.Anonymous) { if (String.IsNullOrEmpty(_simulator.Password)) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Simulator is not anonymous however credentials not supplied."); return(InvokeResult.FromError("Simulator is not anonymous however credentials not supplied.")); } var authCreds = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_simulator.UserName + ":" + _simulator.Password)); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authCreds); } System.Net.Http.HttpResponseMessage responseMessage = null; foreach (var hdr in messageTemplate.MessageHeaders) { client.DefaultRequestHeaders.Add(hdr.HeaderName, ReplaceTokens(_instance, plan, hdr.Value)); } var messageBody = ReplaceTokens(_instance, plan, messageTemplate.TextPayload); messageBody = $"{{'latitude':{lat}, 'longitude':{lon}}}"; await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending Geo Point {messageBody} via {messageTemplate.HttpVerb} to {uri}."); try { switch (messageTemplate.HttpVerb) { case MessageTemplate.HttpVerb_GET: responseMessage = await client.GetAsync(uri); break; case MessageTemplate.HttpVerb_POST: responseMessage = await client.PostAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType)); break; case MessageTemplate.HttpVerb_PUT: responseMessage = await client.PutAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType)); break; case MessageTemplate.HttpVerb_DELETE: responseMessage = await client.DeleteAsync(uri); break; } } catch (HttpRequestException ex) { var fullResponseString = new StringBuilder(); fullResponseString.AppendLine(ex.Message); if (ex.InnerException != null) { fullResponseString.AppendLine(ex.InnerException.Message); } ReceivedContent = fullResponseString.ToString(); await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending GeoPoint: {ex.Message}."); return(InvokeResult.FromException("SendRESTRequestAsync", ex)); } if (responseMessage.IsSuccessStatusCode) { var responseContent = await responseMessage.Content.ReadAsStringAsync(); var fullResponseString = new StringBuilder(); fullResponseString.AppendLine($"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessageSent}"); fullResponseString.AppendLine($"Response Code: {(int)responseMessage.StatusCode} ({responseMessage.ReasonPhrase})"); foreach (var hdr in responseMessage.Headers) { fullResponseString.AppendLine($"{hdr.Key}\t:{hdr.Value.FirstOrDefault()}"); } fullResponseString.AppendLine(); fullResponseString.Append(responseContent); ReceivedContent = fullResponseString.ToString(); if (this._pointIndex < pointArray.Length) { await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Queue up point {_pointIndex} to send."); _timer = new Timer(SendHttpGeoRequest, plan, delay, Timeout.Infinite); } return(InvokeResult.Success); } else { ReceivedContent = $"{responseMessage.StatusCode} - {responseMessage.ReasonPhrase}"; await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending GeoPoint: {ReceivedContent}."); return(InvokeResult.FromError(ReceivedContent)); } } }
public async Task <InvokeResult <Device> > CreateDeviceAsync(DeviceRepository deviceRepo, string deviceTypeId, EntityHeader org, EntityHeader user) { if (!deviceRepo.AutoGenerateDeviceIds) { return(InvokeResult <Device> .FromError("Can only create a device without a device id and name with a repository that is configure to auto generate device ids.")); } var timeStamp = DateTime.UtcNow.ToJSONString(); var device = new Device(); /* Note we just create it here for now then the record gets inserted we go ahead assign the name */ device.DeviceId = $"{deviceRepo.Key}{deviceRepo.IncrementingDeviceNumber:0000000}"; deviceRepo.IncrementingDeviceNumber++; deviceRepo.LastUpdatedBy = user; deviceRepo.LastUpdatedDate = timeStamp; await _deviceRepoRepo.UpdateDeviceRepositoryAsync(deviceRepo); device.Name = device.DeviceId; device.OwnerOrganization = org; device.CreatedBy = user; device.LastUpdatedBy = user; device.CreationDate = timeStamp; device.LastUpdatedDate = timeStamp; if (String.IsNullOrEmpty(device.PrimaryAccessKey)) { var guidBytes = new List <byte>(Guid.NewGuid().ToByteArray()); var timeStampBytes = new List <byte>(BitConverter.GetBytes(DateTime.Now.Ticks)); guidBytes.AddRange(timeStampBytes); device.PrimaryAccessKey = System.Convert.ToBase64String(guidBytes.ToArray()); } if (String.IsNullOrEmpty(device.SecondaryAccessKey)) { var guidBytes = new List <byte>(Guid.NewGuid().ToByteArray()); var timeStampBytes = new List <byte>(BitConverter.GetBytes(DateTime.Now.Ticks)); guidBytes.AddRange(timeStampBytes); device.SecondaryAccessKey = System.Convert.ToBase64String(guidBytes.ToArray()); } var deviceType = await _deviceTypeRepo.GetDeviceTypeAsync(deviceTypeId); if (!EntityHeader.IsNullOrEmpty(deviceType.Firmware)) { device.DesiredFirmware = deviceType.Firmware; } if (!EntityHeader.IsNullOrEmpty(deviceType.FirmwareRevision)) { device.DesiredFirmwareRevision = deviceType.FirmwareRevision; } device.DeviceType = new EntityHeader <DeviceAdmin.Models.DeviceType>() { Id = deviceType.Id, Text = deviceType.Name, Key = deviceType.Key }; device.DeviceConfiguration = deviceType.DefaultDeviceConfiguration; if (deviceRepo.UserOwnedDevicesOnly) { device.AssignedUser = user; device.OwnerUser = user; } var result = await AddDeviceAsync(deviceRepo, device, org, user); if (!result.Successful) { return(InvokeResult <Device> .FromInvokeResult(result)); } return(InvokeResult <Device> .Create(device)); }
private static Expression EnsureInvokeResult(Scope scope, Token tStart, Expression expr, InvokeResult result, Expression instance, string sMember) { switch (result) { case InvokeResult.LuaResult: return ConvertExpression(scope.Runtime, tStart, expr, typeof(LuaResult)); case InvokeResult.Object: if (LuaEmit.IsDynamicType(expr.Type)) return MemberGetSandbox(scope,DynamicExpression.Dynamic(scope.Runtime.GetConvertBinder(typeof(object)), typeof(object), ConvertExpression(scope.Runtime, tStart, expr, typeof(object))), instance, sMember); else return MemberGetSandbox(scope, expr, instance, sMember); default: return MemberGetSandbox(scope, expr, instance, sMember); } }
/// <summary> /// 生成页面快照 /// </summary> /// <param name="pageId"></param> /// <returns></returns> public InvokeResult GenerateSnapshot(int pageId) { InvokeResult result = new InvokeResult(); var pageEntity = this.FindById(pageId); if (pageEntity == null) { result.Status = Status.Failed; result.Message = "页面已被删除"; return(result); } var pageBody = pageEntity.ChildBsonList("PageBody").FirstOrDefault(); if (pageBody == null || string.IsNullOrEmpty(pageBody.Text("body"))) { result.Status = Status.Failed; result.Message = "页面还未创建内容或内容为空"; return(result); } string dir = string.Empty; string orgionPath = GetBookPageOrgionImg(pageId, out dir); dir = System.Web.HttpContext.Current.Server.MapPath(dir); orgionPath = System.Web.HttpContext.Current.Server.MapPath(orgionPath); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } string dir2 = string.Empty; string snapPath = GetBookPageSnapshot(pageId, out dir2); dir2 = System.Web.HttpContext.Current.Server.MapPath(dir2); string thumbPath = System.Web.HttpContext.Current.Server.MapPath(snapPath); if (!System.IO.Directory.Exists(dir2)) { System.IO.Directory.CreateDirectory(dir2); } //string html = System.Web.HttpContext.Current.Server.UrlDecode(pageBody.body); string url = string.Format("http://{0}/account/PageVersionDetail/?pagId={1}", System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"], pageBody.Int("pageId")); HtmlToImg htmlToImg = new HtmlToImg(url, orgionPath, thumbPath, 200, 200); var tag = false; // var tag = htmlToImg.GenerateByUrl(); if (tag == false) { result.Status = Status.Failed; result.Message = "页面快照生成失败"; result.BsonInfo = pageEntity; return(result); } else { var updateBson = new BsonDocument(); updateBson.Add("snapPath", snapPath); result = _ctx.Update(pageEntity, pageEntity); } return(result); }
private static Expression InvokeMemberExpression(Scope scope, Token tStart, Expression instance, string sMember, InvokeResult result, Expression[] arguments) { if (LuaEmit.IsDynamicType(instance.Type)) { return EnsureInvokeResult(scope, tStart, DynamicExpression.Dynamic(scope.Runtime.GetInvokeMemberBinder(sMember, new CallInfo(arguments.Length)), typeof(object), new Expression[] { ConvertExpression(scope.Runtime, tStart, instance, typeof(object)) }.Concat( from c in arguments select Lua.EnsureType(c, typeof(object)) ).ToArray() ), result, instance, sMember ); } else { // look up the method MethodInfo method = LuaEmit.FindMethod( LuaType.GetType(instance.Type).GetInstanceMethods(sMember, false), arguments, getExpressionTypeFunction, true); if (method != null) return EnsureInvokeResult(scope, tStart, SafeExpression(() => InvokeMemberExpressionBind(method, scope.Runtime, instance, arguments), tStart), result, instance, sMember); else return InvokeMemberExpressionDynamic(scope, tStart, instance, sMember, result, arguments); } }
public void Init() { _dataStreamManager = new DataStreamManager(new Mock <IDataStreamRepo>().Object, new Mock <ISharedConnectionManager>().Object, _connectionSettings.Object, _orgUtils.Object, new AdminLogger(new Utils.LogWriter()), _secureStorage, new Mock <IAppConfig>().Object, new Mock <IDependencyManager>().Object, _security.Object); _security.Setup(sec => sec.AuthorizeAsync(It.IsAny <EntityHeader>(), It.IsAny <EntityHeader>(), It.IsAny <string>(), It.IsAny <object>())); _org = EntityHeader.Create(OrgId, "TEST ORG"); _user = EntityHeader.Create(UserId, "TEST USER"); _orgUtils.Setup(om => om.GetOrgNamespaceAsync(It.Is <string>(str => str == OrgId))).ReturnsAsync(InvokeResult <string> .Create(_orgNamespace)); var connSettings = new ConnectionSettings() { Uri = _dbUrl, UserName = _dbUserName, Password = _dbPassword, }; _connectionSettings.SetupGet(cs => cs.PointArrayConnectionSettings).Returns(connSettings); }
public async Task<InvokeResult> InvokeAsync(InvokeOptions options) { using (var form = _formFactory.Invoke()) using (var browser = new ExtendedWebBrowser() { Dock = DockStyle.Fill }) { var signal = new SemaphoreSlim(0, 1); var result = new InvokeResult { ResultType = InvokeResultType.UserCancel }; form.FormClosed += (o, e) => { signal.Release(); }; browser.NavigateError += (o, e) => { e.Cancel = true; result.ResultType = InvokeResultType.HttpError; result.Error = e.StatusCode.ToString(); signal.Release(); }; browser.BeforeNavigate2 += (o, e) => { if (e.Url.StartsWith(options.EndUrl)) { e.Cancel = true; result.ResultType = InvokeResultType.Success; if (options.ResponseMode == ResponseMode.FormPost) { result.Response = Encoding.UTF8.GetString(e.PostData ?? new byte[] { }); } else { result.Response = e.Url; } signal.Release(); } }; form.Controls.Add(browser); browser.Show(); System.Threading.Timer timer = null; if (options.InitialDisplayMode != DisplayMode.Visible) { result.ResultType = InvokeResultType.Timeout; timer = new System.Threading.Timer((o) => { var args = new HiddenModeFailedEventArgs(result); HiddenModeFailed?.Invoke(this, args); if (args.Cancel) { browser.Stop(); form.Invoke(new Action(() => form.Close())); } else { form.Invoke(new Action(() => form.Show())); } }, null, (int)options.InvisibleModeTimeout.TotalSeconds * 1000, Timeout.Infinite); } else { form.Show(); } browser.Navigate(options.StartUrl); await signal.WaitAsync(); if (timer != null) timer.Change(Timeout.Infinite, Timeout.Infinite); form.Hide(); browser.Hide(); return result; } }
public void LogInvokeResult <TResultType>(string tag, InvokeResult <TResultType> result, params KeyValuePair <string, string>[] args) { throw new NotImplementedException(); }
private static Expression ParseExpression(Scope scope, LuaLexer code, InvokeResult result, bool lDebug) { Token tStart = code.Current; bool lWrap = false; Expression expr = ParseExpression(scope, code, result, ref lWrap); if (lWrap && lDebug) return WrapDebugInfo(true, false, tStart, code.Current, expr); else return expr; }
public InvokeResult BatchCreate(EasyUIgridCollectionParam <StringObjectDictionary> param) { InvokeResult result = new InvokeResult { Success = true }; string sql = "insert into Pub_SmsSend( ScheduleTime,Mobile,BatchNum,SendContent, " + " SourceCatalog,SourceTable,SourceId,SendCatalog ) " + " select null ScheduleTime,Mobile,'{0}' BatchNum,null SendContent, " + " null SourceCatalog,'Oca_OldManConfigInfo' SourceTable,SourceId,'0' SendCatalog " + " from ( select row_number()over(order by tmpcolumn desc) as Rowid,* from ( " + " select top {1} tmpcolumn=0,a.OldManId SourceId,b.CallNo Mobile"; int total = 0; int toprecord = 0; if (param.page > 0 && param.rows > 0) { total = param.page * param.rows; toprecord = (param.rows - 1) * param.page; } try { /***********************begin 复杂查询添加代码*********************/ /**********************************************************/ List <string> filtersClause = new List <string>(); if (param.filterFields != null) { //获取默认发送短信类的属性字段 var className = typeof(SmsSend).GetProperties(); foreach (var field in param.filterFields) { if (className.Count(s => s.Name == field.key) > 0) { sql = sql.Replace((" null " + field.key).Trim(), string.Format(" '{0}' {1}", field.value, field.key)); continue; } filtersClause.Add(string.Format(" a.{0} = '{1}'", field.key.Replace("OldManStatus", "Status"), field.value)); } } sql += " from Oca_OldManBaseInfo a left join Oca_OldManConfigInfo b on a.OldManId = b.OldManId "; if (filtersClause.Count > 0) { sql += " where " + string.Join(" AND ", filtersClause.ToArray()); } /***********************begin 模糊查询*********************/ List <string> whereClause = new List <string>(); if (param.fuzzyFields != null) { foreach (var field in param.fuzzyFields) { whereClause.Add(string.Format("{0} like '%{1}%' ", field.key, field.value)); } } /***********************end 模糊查询***********************/ /***********************begin 自定义代码*******************/ /***********************此处添加自定义查询代码*************/ /***********************end 自定义代码*********************/ if (whereClause.Count > 0) { sql += (filtersClause.Count > 0 ? " AND " : " where ") + string.Join(" AND ", whereClause.ToArray()); } /**********************************************************/ /***********************begin 排序*************************/ /**********************************************************/ if (!string.IsNullOrEmpty(param.sort)) { sql += " order by " + param.sort + " " + param.order ?? "ASC"; } sql += " )t )tt where Rowid >{2} and Mobile is not null and Mobile<>'' "; sql = string.Format(sql, (new Random(Guid.NewGuid().GetHashCode())).Next(), total, toprecord); /***********************end 排序***************************/ BuilderFactory.DefaultBulder().ExecuteNativeSqlNoneQuery(sql); } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.Message; } return(result); }
private static Expression ParseExpressionBitAnd(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // exprBitAnd ::= exprCmp { & exprCmp } var expr = ParseExpressionCmp(scope, code, result, ref lWrap); while (code.Current.Typ == LuaToken.BitAnd) { code.Next(); expr = BinaryOperationExpression(scope.Runtime, code.Current, ExpressionType.And, expr, ParseExpressionCmp(scope, code, InvokeResult.Object, ref lWrap) ); lWrap |= true; } return expr; }
public async Task <InvokeResult> AddMediaMessageAsync(Stream stream, string contentType, long contentLength, DateTime startTimeStamp, string path, String deviceId = "", String topic = "", Dictionary <string, string> headers = null) { try { var message = new PipelineExecutionMessage() { PayloadType = MessagePayloadTypes.Media, CreationTimeStamp = startTimeStamp.ToJSONString() }; Metrics.MessagesProcessed++; message.PayloadLength = contentLength; Metrics.BytesProcessed += message.PayloadLength + (String.IsNullOrEmpty(topic) ? 0 : topic.Length); message.Envelope.DeviceId = deviceId; message.Envelope.Topic = topic; message.Envelope.Path = path; var headerLength = 0; if (headers != null) { if (headers.ContainsKey("method")) { message.Envelope.Method = headers["method"]; } if (headers.ContainsKey("topic")) { message.Envelope.Topic = headers["topic"]; foreach (var header in headers) { headerLength += header.Key.Length + (String.IsNullOrEmpty(header.Value) ? 0 : header.Value.Length); } } foreach (var hdr in headers) { message.Envelope.Headers.Add(hdr.Key, hdr.Value); } } var listenerInstruction = new PipelineExecutionInstruction() { Name = _listenerConfiguration.Name, Type = GetType().Name, QueueId = "N/A", StartDateStamp = startTimeStamp.ToJSONString(), ProcessByHostId = PEMBus.Instance.PrimaryHost.Id, ExecutionTimeMS = (DateTime.UtcNow - startTimeStamp).TotalMilliseconds, }; message.Instructions.Add(listenerInstruction); var plannerQueue = PEMBus.Queues.Where(queue => queue.ForModuleType == PipelineModuleType.Planner).FirstOrDefault(); var planner = PEMBus.Instance.Solution.Value.Planner.Value; var plannerInstruction = new PipelineExecutionInstruction() { Name = "Planner", Type = "Planner", QueueId = plannerQueue.PipelineModuleId, Enqueued = DateTime.UtcNow.ToJSONString() }; message.CurrentInstruction = plannerInstruction; message.Instructions.Add(plannerInstruction); double?lat = null, lon = null; if (headers != null && headers.ContainsKey("x-latitude") && headers.ContainsKey("x-longitude")) { if (double.TryParse(headers["x-latitude"], out double tmpLatitude) && double.TryParse(headers["x-longitude"], out double tmpLongitude)) { lat = tmpLatitude; lon = tmpLongitude; } } var insertResult = await PEMBus.DeviceMediaStorage.StoreMediaItemAsync(stream, message.Id, contentType, contentLength, lat, lon); if (!insertResult.Successful) { return(insertResult.ToInvokeResult()); } message.MediaItemId = insertResult.Result; await plannerQueue.EnqueueAsync(message); return(InvokeResult.Success); } catch (Exception ex) { PEMBus.InstanceLogger.AddException("ListenerModule_AddBinaryMessageAsync", ex); return(InvokeResult.FromException("ListenerModule_AddBinaryMessageAsync", ex)); } }
private static Expression ParseExpressionCast(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // cast ::= cast(type, expr) if (code.Current.Typ == LuaToken.KwCast) { Token tStart = code.Current; lWrap |= true; PrefixMemberInfo prefix = new PrefixMemberInfo(tStart, ParsePrefixCast(scope, code), null, null, null); ParseSuffix(scope, code, prefix); return prefix.GenerateGet(scope, result); } else return ParsePrefix(scope, code).GenerateGet(scope, result); }
private async Task <InvokeResult> HandleSystemMessageAsync(string path, string payload) { Metrics.MessagesProcessed++; PEMBus.InstanceLogger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Message, "ListenerMOdule_HandleSystemMessageAsync", "Received System Message", path.ToKVP("topic"), payload.ToKVP("body")); var parts = path.Split('/'); if (parts.Length < 5) { var errMsg = $"NuvIoT service messages must be at least 5 segments {path} is {parts.Length} segments"; PEMBus.InstanceLogger.AddError("ListenerModule__HandleSystemMessage", errMsg); return(InvokeResult.FromError(errMsg)); } var deviceId = parts[3]; var device = await PEMBus.DeviceStorage.GetDeviceByDeviceIdAsync(deviceId); if (device == null) { var errMsg = $"Could not find device with device id {deviceId}."; PEMBus.InstanceLogger.AddError("ListenerModule__HandleSystemMessage", errMsg); return(InvokeResult.FromError(errMsg)); } device.LastContact = DateTime.UtcNow.ToJSONString(); if (parts[4] == "state") { device.DeviceTwinDetails.Insert(0, new DeviceManagement.Models.DeviceTwinDetails() { Timestamp = DateTime.UtcNow.ToJSONString(), Details = payload }); var payloadSegements = payload.Split(','); foreach (var segement in payloadSegements) { var fieldParts = segement.Split('='); if (fieldParts.Length == 2) { var nameParts = fieldParts[0].Split('-'); if (nameParts.Length == 2) { var typeName = nameParts[0]; var key = nameParts[1]; var value = fieldParts[1]; if (typeName != "readonly") { var prop = device.Properties.FirstOrDefault(prp => prp.Key == key); if (prop != null) { if (prop.Value != value) { prop.Value = value; prop.LastUpdated = DateTime.UtcNow.ToJSONString(); prop.LastUpdatedBy = "Device Twin"; } } } else { if (key == "firmwareSku") { device.ActualFirmware = value; device.ActualFirmwareDate = DateTime.Now.ToJSONString(); } if (key == "firmwareVersion") { device.ActualFirmwareRevision = value; device.ActualFirmwareDate = DateTime.Now.ToJSONString(); } } } } } } else if (parts[4] == "err") { var err = parts[5]; var action = parts[6]; var exception = new DeviceException() { ErrorCode = err, DeviceId = device.DeviceId, DeviceUniqueId = device.Id, DeviceRepositoryId = device.DeviceRepository.Id, Timestamp = DateTime.UtcNow.ToString(), }; exception.AdditionalDetails.Add(payload); if (action == "raise") { await PEMBus.InstanceConnector.HandleDeviceExceptionAsync(exception); } else if (action == "clear") { await PEMBus.InstanceConnector.ClearDeviceExceptionAsync(exception); } } else if (parts[4] == "iovalues") { var values = payload.Split(','); if (values.Length != 16) { throw new InvalidDataException($"IO Configuration from device should consist of 16 comma delimited values, message consists of ${values.Length} items."); } for (int idx = 0; idx < 8; ++idx) { if (!String.IsNullOrEmpty(values[idx + 8])) { var sensor = device.SensorCollection.Where(sns => sns.Technology != null && sns.Technology.Value == DeviceManagement.Models.SensorTechnology.ADC && sns.PortIndex == idx).FirstOrDefault(); if (sensor != null) { sensor.Value = values[idx + 8]; sensor.LastUpdated = DateTime.UtcNow.ToJSONString(); } } } for (int idx = 0; idx < 8; ++idx) { if (!String.IsNullOrEmpty(values[idx])) { var sensor = device.SensorCollection.Where(sns => sns.Technology != null && sns.Technology.Value == DeviceManagement.Models.SensorTechnology.IO && sns.PortIndex == idx).FirstOrDefault(); if (sensor != null) { sensor.Value = values[idx]; sensor.LastUpdated = DateTime.UtcNow.ToJSONString(); } } } await PEMBus.SensorEvaluator.EvaluateAsync(device); } else if (parts[4] == "geo") { var values = payload.Split(','); if (values.Length < 2) { throw new InvalidDataException($"Geo Location Data type must contain a minimum of 2 fields for latitude and longitude, message consists of ${values.Length} items."); } if (!double.TryParse(values[0], out double lat)) { throw new InvalidDataException($"Invalid Latitude value [{values[0]}]."); } if (lat > 90 || lat < -90) { throw new InvalidDataException($"Invalid Latitude value [{values[0]}], must be between -90 and 90."); } if (!double.TryParse(values[1], out double lon)) { throw new InvalidDataException($"Invalid Longitude value [{values[1]}]."); } if (lon > 180 || lon < -180) { throw new InvalidDataException($"Invalid Latitude value [{values[1]}], must be between -180 and 180."); } device.GeoLocation = new LagoVista.Core.Models.Geo.GeoLocation() { LastUpdated = DateTime.UtcNow.ToJSONString(), Latitude = lat, Longitude = lon, }; } else if (parts[4] == "online") { device.ConnectionTimeStamp = DateTime.UtcNow.ToJSONString(); var rssi = -1.0; var reconnect = false; var payloadSegements = payload.Split(','); foreach (var segement in payloadSegements) { var fieldParts = segement.Split('='); if (fieldParts.Length == 2) { var nameParts = fieldParts[0].Split('-'); if (nameParts.Length == 2) { var typeName = nameParts[0]; var key = nameParts[1]; var value = fieldParts[1]; if (typeName != "readonly") { var prop = device.Properties.FirstOrDefault(prp => prp.Key == key); if (prop != null) { if (prop.Value != value) { if (prop.AttributeType.Value == DeviceAdmin.Models.ParameterTypes.TrueFalse) { if (value == "1") { value = "true"; } else if (value == "0") { value = "false"; } else { value = value.ToLower(); } } prop.Value = value; prop.LastUpdated = DateTime.UtcNow.ToJSONString(); prop.LastUpdatedBy = "Device Twin"; } } } else { if (key == "firmwareSku") { device.ActualFirmware = value; device.ActualFirmwareDate = DateTime.Now.ToJSONString(); } if (key == "firmwareVersion") { device.ActualFirmwareRevision = value; device.ActualFirmwareDate = DateTime.Now.ToJSONString(); } if (key == "rssi") { double.TryParse(value, out rssi); } if (key == "reconnect") { reconnect = value != "0"; } } } } } var connectionEvent = new DeviceConnectionEvent() { DeviceId = device.Id, FirmwareRevision = device.ActualFirmwareRevision, FirmwareSKU = device.ActualFirmware, TimeStamp = DateTime.UtcNow.ToJSONString(), RSSI = rssi, Reconnect = reconnect }; await PEMBus.DeviceConnectionEvent.AddDeviceEventConnectionEvent(connectionEvent); } await PEMBus.DeviceStorage.UpdateDeviceAsync(device); var json = JsonConvert.SerializeObject(Models.DeviceForNotification.FromDevice(device), _camelCaseSettings); var notification = new Notification() { Payload = json, Channel = EntityHeader <Channels> .Create(Channels.Device), ChannelId = device.Id, PayloadType = "Device", DateStamp = DateTime.UtcNow.ToJSONString(), MessageId = Guid.NewGuid().ToId(), Text = "Device Updated", Title = "Device Updated" }; await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification); notification = new Notification() { Payload = json, Channel = EntityHeader <Channels> .Create(Channels.DeviceRepository), ChannelId = device.DeviceRepository.Id, PayloadType = "Device", DateStamp = DateTime.UtcNow.ToJSONString(), MessageId = Guid.NewGuid().ToId(), Text = "Device Updated", Title = "Device Updated" }; await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification); foreach (var group in device.DeviceGroups) { notification = new Notification() { Payload = json, Channel = EntityHeader <Channels> .Create(Channels.DeviceGroup), ChannelId = group.Id, PayloadType = "Device", DateStamp = DateTime.UtcNow.ToJSONString(), MessageId = Guid.NewGuid().ToId(), Text = "Device Updated", Title = "Device Updated" }; await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification); } return(InvokeResult.Success); }
private static Expression ParseExpressionCon(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // exprCon::= exprShift { '..' exprShift } List<Expression> exprs = new List<Expression>(); exprs.Add(ParseExpressionShift(scope, code, result, ref lWrap)); while (code.Current.Typ == LuaToken.DotDot) { code.Next(); exprs.Add(ParseExpressionShift(scope, code, InvokeResult.Object, ref lWrap)); } // Erzeuge Concat if (exprs.Count > 1) { lWrap |= true; return ConcatOperationExpression(scope.Runtime, code.Current, exprs.ToArray()); } else return exprs[0]; }
public async Task <InvokeResult> AddBinaryMessageAsync(byte[] buffer, DateTime startTimeStamp, String deviceId = "", String topic = "") { if (!String.IsNullOrEmpty(topic) && topic.StartsWith("nuviot/srvr/dvcsrvc")) { var strPayload = System.Text.ASCIIEncoding.ASCII.GetString(buffer); return(await HandleSystemMessageAsync(topic, strPayload)); } try { var message = new PipelineExecutionMessage() { PayloadType = MessagePayloadTypes.Binary, BinaryPayload = buffer, CreationTimeStamp = startTimeStamp.ToJSONString() }; Metrics.MessagesProcessed++; if (buffer != null) { message.PayloadLength = buffer.Length; } Metrics.BytesProcessed = message.PayloadLength + (String.IsNullOrEmpty(topic) ? 0 : topic.Length); if (!String.IsNullOrEmpty(deviceId)) { message.Envelope.DeviceId = deviceId; } message.Envelope.Topic = topic; var listenerInstruction = new PipelineExecutionInstruction() { Name = _listenerConfiguration.Name, Type = GetType().Name, QueueId = "N/A", StartDateStamp = startTimeStamp.ToJSONString(), ProcessByHostId = PEMBus.Instance.PrimaryHost.Id, ExecutionTimeMS = (DateTime.UtcNow - startTimeStamp).TotalMilliseconds, }; message.Instructions.Add(listenerInstruction); var plannerQueue = PEMBus.Queues.Where(queue => queue.ForModuleType == PipelineModuleType.Planner).FirstOrDefault(); var planner = PEMBus.Instance.Solution.Value.Planner.Value; var plannerInstruction = new PipelineExecutionInstruction() { Name = "Planner", Type = "Planner", QueueId = plannerQueue.PipelineModuleId, Enqueued = DateTime.UtcNow.ToJSONString() }; message.CurrentInstruction = plannerInstruction; message.Instructions.Add(plannerInstruction); await plannerQueue.EnqueueAsync(message); return(InvokeResult.Success); } catch (Exception ex) { PEMBus.InstanceLogger.AddException("ListenerModule_AddBinaryMessageAsync", ex); return(InvokeResult.FromException("ListenerModule_AddBinaryMessageAsync", ex)); } }
private static Expression ParseExpressionOr(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // exprOr ::= exprAnd { or exprAnd } var expr = ParseExpressionAnd(scope, code, result, ref lWrap); while (code.Current.Typ == LuaToken.KwOr) { code.Next(); expr = BinaryOperationExpression(scope.Runtime, code.Current, ExpressionType.OrElse, expr, ParseExpressionAnd(scope, code, InvokeResult.Object, ref lWrap)); lWrap |= true; } return expr; }
public async Task <InvokeResult> AddStringMessageAsync(string buffer, DateTime startTimeStamp, string path = "", string deviceId = "", string topic = "", Dictionary <string, string> headers = null) { try { if (!String.IsNullOrEmpty(topic)) { Console.WriteLine($"Received Message with topic [{topic}]"); } if (!String.IsNullOrEmpty(topic) && topic.StartsWith("nuviot/srvr/dvcsrvc")) { return(await HandleSystemMessageAsync(topic, buffer)); } if (!String.IsNullOrEmpty(path) && path.StartsWith("/nuviot/srvr/dvcsrvc")) { return(await HandleSystemMessageAsync(path.TrimStart('/'), buffer)); } var message = new PipelineExecutionMessage() { PayloadType = MessagePayloadTypes.Text, TextPayload = buffer, CreationTimeStamp = startTimeStamp.ToJSONString() }; var headerLength = 0; if (headers != null) { if (headers.ContainsKey("method")) { message.Envelope.Method = headers["method"]; } if (headers.ContainsKey("topic")) { message.Envelope.Topic = headers["topic"]; foreach (var header in headers) { headerLength += header.Key.Length + (String.IsNullOrEmpty(header.Value) ? 0 : header.Value.Length); } } if (headers != null) { foreach (var hdr in headers) { message.Envelope.Headers.Add(hdr.Key, hdr.Value); } } } message.PayloadLength = String.IsNullOrEmpty(buffer) ? 0 : buffer.Length; var bytesProcessed = message.PayloadLength + (String.IsNullOrEmpty(path) ? 0 : path.Length) + headerLength; Metrics.BytesProcessed += bytesProcessed; Metrics.MessagesProcessed++; var json = JsonConvert.SerializeObject(Metrics); /* * Console.WriteLine("LISTENER => " + Id); * Console.ForegroundColor = ConsoleColor.Yellow; * Console.WriteLine(json); * Console.WriteLine("----------------------------"); */ message.Envelope.DeviceId = deviceId; message.Envelope.Path = path; message.Envelope.Topic = topic; var listenerInstruction = new PipelineExecutionInstruction() { Name = _listenerConfiguration.Name, Type = GetType().Name, QueueId = _listenerConfiguration.Id, StartDateStamp = startTimeStamp.ToJSONString(), ProcessByHostId = PEMBus.Instance.PrimaryHost.Id, Enqueued = startTimeStamp.ToJSONString(), ExecutionTimeMS = (DateTime.UtcNow - startTimeStamp).TotalMilliseconds, }; message.Instructions.Add(listenerInstruction); var plannerQueue = PEMBus.Queues.Where(queue => queue.ForModuleType == PipelineModuleType.Planner).FirstOrDefault(); if (plannerQueue == null) { PEMBus.InstanceLogger.AddError("ListenerModule_AddStringMessageAsync", "Could not find planner queue."); return(InvokeResult.FromError("Could not find planner queue.")); } var planner = PEMBus.Instance.Solution.Value.Planner.Value; var plannerInstruction = new PipelineExecutionInstruction() { Name = planner.Name, Type = "Planner", QueueId = plannerQueue.PipelineModuleId, Enqueued = DateTime.UtcNow.ToJSONString() }; message.CurrentInstruction = plannerInstruction; message.Instructions.Add(plannerInstruction); await plannerQueue.EnqueueAsync(message); return(InvokeResult.Success); } catch (Exception ex) { Metrics.DeadLetterCount++; Metrics.ErrorCount++; PEMBus.InstanceLogger.AddException("ListenerModule_AddStringMessageAsync", ex); Console.WriteLine(ex.StackTrace); return(InvokeResult.FromException("ListenerModule_AddStringMessageAsync", ex)); } }
private static Expression ParseExpressionPower(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // expPow ::= cast [ ^ expPow ] Expression expr = ParseExpressionCast(scope, code, result, ref lWrap); if (code.Current.Typ == LuaToken.Caret) { code.Next(); lWrap |= true; return BinaryOperationExpression(scope.Runtime, code.Current, ExpressionType.Power, expr, ParseExpressionPower(scope, code, InvokeResult.Object, ref lWrap)); } else return expr; }
/// <summary> /// 新增 /// </summary> /// <param name="entity"></param> /// <returns></returns> public InvokeResult Insert(BsonDocument entity, BsonDocument instance, int userId) { InvokeResult result = new InvokeResult(); if (entity == null || instance == null) { throw new ArgumentNullException(); } if (HasExistObj(entity.Int("flowInstanceId"), entity.Int("grantUserId"), entity.Int("givenUserId")).Count() > 0) { result.Status = Status.Failed; result.Message = "不能重复转办给同一个人"; return(result); } //获取需要删除的列表 将status 设置为1,当“A转给B” “B再转给c”的时候需要将”A转给B“过滤 var hitDisabledQuery = FindAll().Where(c => c.Int("givenUserId") == entity.Int("grantUserId") && c.Int("status") == 0).OrderByDescending(c => c.Date("createDate")); using (TransactionScope tran = new TransactionScope()) { try { //设置无效转办 if (hitDisabledQuery.Count() > 0) { var tempResult = dataOp.QuickUpdate("BusinessFlowTurnRight", hitDisabledQuery.ToList(), "status=1"); if (tempResult.Status != Status.Successful) { return(tempResult); } } result = dataOp.Insert("BusinessFlowTurnRight", entity); var givenUserName = dataOp.FindOneByKeyVal("SysUser", "userId", entity.Text("givenUserId")); BsonDocument flowTrace = new BsonDocument(); flowTrace.Add("flowInstanceId", instance.Int("flowInstanceId")); flowTrace.Add("traceType", 6); flowTrace.Add("remark", entity.Text("remark")); flowTrace.Add("preStepId", instance.Int("stepId")); flowTrace.Add("result", string.Format("将操作权转办给了{0}", givenUserName != null ? givenUserName.Text("name") : string.Empty)); var traceResult = BusFlowTraceBll._(dataOp).Insert(flowTrace); if (traceResult.Status == Status.Successful) { tran.Complete(); } else { result.Status = Status.Failed; result.Message = "传入参数有误"; } } catch (NullReferenceException ex) { result.Status = Status.Failed; result.Message = "传入参数有误"; } catch (Exception ex) { result.Status = Status.Failed; result.Message = "传入参数有误"; } } return(result); }
private static Expression ParseExpressionUnary(Scope scope, LuaLexer code, InvokeResult result, ref bool lWrap) { // expUn ::= { 'not' | - | # | ~ } expPow LuaToken typ = code.Current.Typ; if (typ == LuaToken.KwNot || typ == LuaToken.Minus || typ == LuaToken.Dilde || typ == LuaToken.Cross) { code.Next(); Expression expr = ParseExpressionUnary(scope, code, InvokeResult.Object, ref lWrap); lWrap |= true; ExpressionType exprType; if (typ == LuaToken.KwNot) exprType = ExpressionType.Not; else if (typ == LuaToken.Minus) exprType = ExpressionType.Negate; else if (typ == LuaToken.Dilde) exprType = ExpressionType.OnesComplement; else exprType = ExpressionType.ArrayLength; lWrap |= true; return UnaryOperationExpression(scope.Runtime, code.Current, exprType, expr); } else return ParseExpressionPower(scope, code, result, ref lWrap); }
/// <summary> /// 多个部门 /// </summary> /// <param name="user"></param> /// <param name="type"></param> /// <param name="defaultState"></param> /// <returns></returns> public InvokeResult UserAddMulDep(ADUser user, int type, int defaultState, int userType) { InvokeResult result = new InvokeResult(); try { string guid = user.Guid; var oldUser = userType == 0 ? _dataOp.FindOneByKeyVal("SysUser", "guid", guid) : _dataOp.FindOneByKeyVal("SysUser", "loginName", user.LoginName); BsonDocument doc = new BsonDocument(); doc.Add("name", user.Name); doc.Add("loginName", user.LoginName); //doc.Add("mobileNumber", user.MobieNumber); doc.Add("phoneNumber", user.PhoneNumber); doc.Add("guid", user.Guid); doc.Add("adpath", user.Path); doc.Add("state", defaultState.ToString()); doc.Add("status", user.Status.ToString()); Console.WriteLine("人员:{0}——>{1}", user.Name, user.Guid); if (!string.IsNullOrEmpty(user.MobieNumber)) { doc.Add("mobileNumber", user.MobieNumber); } if (!string.IsNullOrEmpty(user.EmailAddr)) { doc.Add("emailAddr", user.EmailAddr); } if (oldUser == null)//新增 { doc.Add("loginPwd", "8888"); result = _dataOp.Insert("SysUser", doc); } else { if (userType == 0) { result = _dataOp.Update("SysUser", "db.SysUser.distinct('_id',{'guid':'" + user.Guid + "'})", doc); } else { result = _dataOp.Update("SysUser", "db.SysUser.distinct('_id',{'loginName':'" + user.LoginName + "'})", doc); } } if (result.Status != Status.Failed) { foreach (var item in user.DepartMentGuids) { BsonDocument org = new BsonDocument(); switch (type) { case 0: org = _dataOp.FindOneByKeyVal("Organization", "name", item); break; case 1: org = _dataOp.FindOneByKeyVal("Organization", "guid", item); break; case 2: org = _dataOp.FindOneByKeyVal("Organization", "code", item); break; } if (org != null) { var post = _dataOp.FindOneByKeyVal("OrgPost", "orgId", org.Text("orgId")); if (post != null) { var subPost = _dataOp.FindOneByQueryStr("UserOrgPost", string.Format("userId={0}&postId={1}", result.BsonInfo.Text("userId"), post.Text("postId"))); if (subPost == null) { BsonDocument relDoc = new BsonDocument(); relDoc.Add("userId", result.BsonInfo.Text("userId")); relDoc.Add("postId", post.Text("postId")); //result = _dataOp.Insert("UserOrgPost", relDoc); if (SysAppConfig.CustomerCode == CustomerCode.ZHHY.ToString() && oldUser != null) { } else { result = _dataOp.Insert("UserOrgPost", relDoc); } } } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(result); }