public Word Visit(ForNode forNode) { ControlStack.Push(ControlType.Loop); Word result; PyObj pyObjCond; MyBoolean myBoolCond; // Declara o asigna la flag en un scope intermedio entre el scope que contiene al for y el del bloque del for PushScope(); result = forNode.Flag.Accept(this); if (IsError(result)) { PopScope(); ControlStack.Pop(); return(result); } while (true) { result = forNode.Condition.Accept(this); if (IsError(result)) { PopScope(); ControlStack.Pop(); return(result); } if (IsMemoryBlock(result))//comentar ese if else si se hace la desereferencia en atomic expr. { pyObjCond = ((MemoryBlock)result).Value; } else { pyObjCond = (PyObj)result; } //pyObjCond = (PyObj)result;//Descomentar esta linea si se hace la desereferencia en atomic expr. if (pyObjCond.GetMyType() != TypeConstants.BOOLEAN) { PopScope(); ControlStack.Pop(); return(ErrorFactory.ForConditionError(forNode, pyObjCond)); } myBoolCond = (MyBoolean)pyObjCond; if (!myBoolCond.Bool) { break; } result = forNode.Block.Accept(this); if (IsJumper(result)) { var jumper = (Jumper)result; if (jumper.GetJumperType() == JumperType.Breaker) { PopScope(); return(null); } else if (jumper.GetJumperType() != JumperType.Continue) { PopScope(); return(jumper); } //Si es continue no tiene que hacer nada porque el block ya interumpio la ejecucion 1 vez } result = forNode.Update.Accept(this); if (IsError(result)) { PopScope(); ControlStack.Pop(); return(result); } } PopScope(); ControlStack.Pop(); return(null); }
public async Task <HttpResponseMessage> EditHotel(IncomingEditHotel hotel) { return(await ErrorFactory.Handle(async() => { var userId = User?.Identity?.GetUserId(); if (userId == null) { throw new Exception("User not found."); } if (hotel == null) { throw new InvalidModelException("hotel cannot be null"); } if (hotel.TaxRate < 0 || hotel.TaxRate > 1) { throw new InvalidModelException("Tax rate must be greater than 0 and less than 1"); } using (var unitOfWork = new UnitOfWork()) { var finHotel = unitOfWork.Hotels.EditHotel(userId, hotel); unitOfWork.Complete(); try { if (hotel.Image != null && !string.IsNullOrWhiteSpace(hotel.Image.Data)) { //This is added to help yogita with her base64 problems. hotel.Image.Data = hotel.Image.Data.Replace(' ', '+'); var data = ImageFactory.ConvertBase64ToArray(hotel.Image.Data); GalleryManager galMan = new GalleryManager(); var pictureId = await galMan.UploadImage(data, userId); if (pictureId == null) { throw new Exception(); } var tempHotel = unitOfWork.Hotels.SetHotelImageADMIN(userId, finHotel.Id, pictureId ?? Guid.NewGuid()); unitOfWork.Complete(); finHotel = tempHotel; } } catch (Exception) { //Maybe try to delete image. } return JsonFactory.CreateJsonMessage(OutgoingHotel.Parse(finHotel), HttpStatusCode.OK, this.Request); } }, this.Request)); }
public Word Visit(SwitchNode switchNode) { ControlStack.Push(ControlType.Switch);//Push into control stack var result = switchNode.Flag.Accept(this); if (IsError(result)) { ControlStack.Pop(); return(result); } PyObj pyObjFlag; if (IsMemoryBlock(result))//comentar ese if else si se hace la desereferencia en atomic expr. { pyObjFlag = ((MemoryBlock)result).Value; } else { pyObjFlag = (PyObj)result; } //pyObj = (PyObj)result;//Descomentar esta linea si se hace la desereferencia en atomic expr. var switchElements = new AstNode[switchNode.SwitchElements.Count]; switchNode.SwitchElements.CopyTo(switchElements); //Caso que dio true a pyObjFlag cuando se comparar con == int? trueCaseIndex = null; int? defaultIndex = null; SwitchLabel switchLabel; PyObj pyObjCase; MyBoolean caseEvaluationResult; for (int i = 0; i < switchElements.Length; i++) { //Quitar comentario si se desea que no puedan venir declaraciones dentro del if //if (switchElements[i].GetNodeType() == NodeType.Declaration) //{ // ControlStack.Pop(); // return ErrorFactory.DeclarationInSwitch(switchElements[i]); //} if (switchElements[i].GetNodeType() != NodeType.SwitchLabel) { continue; } result = switchElements[i].Accept(this); if (IsError(result)) { ControlStack.Pop(); return(result); } switchLabel = (SwitchLabel)result; if (switchLabel.GetLabelType() == LabelType.Default) { if (defaultIndex != null) { ControlStack.Pop(); return(ErrorFactory.MultipleDefaultInSwitch(switchElements[i])); } else { defaultIndex = i; } } else { pyObjCase = switchLabel.Value; result = pyObjFlag.BinaryOperation(BinaryOperator.PyEquals, pyObjCase); if (IsError(result)) { ControlStack.Pop(); return(ErrorFactory.Create(switchElements[i], (MyError)result)); } if (((PyObj)result).GetMyType() != TypeConstants.BOOLEAN) { ControlStack.Pop(); return(ErrorFactory.NotValidOperationInSwitch(switchElements[i])); } caseEvaluationResult = (MyBoolean)result; if (caseEvaluationResult.Bool) { if (trueCaseIndex != null) { ControlStack.Pop(); return(ErrorFactory.MultipleTrueCasesInSwitch(switchElements[i])); } else { trueCaseIndex = i; } } } } int startIndex = switchElements.Length; if (trueCaseIndex != null) { startIndex = (int)trueCaseIndex; } else if (defaultIndex != null) { startIndex = (int)defaultIndex; } for (int i = startIndex; i < switchElements.Length; i++) { if (switchElements[i].GetNodeType() == NodeType.SwitchLabel) { continue; } result = switchElements[i].Accept(this); if (IsJumper(result)) { var jumper = (Jumper)result; if (jumper.CanJump(ControlType.Switch)) { if (!jumper.WasPopped())//Chapuz alto en el caso que retorne un jumper que no este metido dentro de ningun scope { ControlStack.Pop(); } return(null); } if (jumper.WasPopped())//Chapuz Alto para que no haga pop until mas de una vez cuando hay bloques adentro de bloques { return(jumper); } if (ControlStack.PopUntil(jumper)) { return(jumper); } else { ErrorFactory.NotValidJumper(switchElements[i], jumper); } } } return(null); }
/// <summary> /// BuildXL's classification of different <see cref="IpcResultStatus"/> values: /// - <see cref="IpcResultStatus.InvalidInput"/> --> <see cref="Keywords.UserError"/> /// - <see cref="IpcResultStatus.TransmissionError"/> --> <see cref="Keywords.InfrastructureError"/> /// - all other errors --> InternalError /// </summary> private static async Task <TResult> HandleKnownErrorsAsync <TResult>(Func <Task <TResult> > factory, ErrorFactory <TResult> errorValueFactory) { try { return(await factory()); } catch (VssUnauthorizedException e) { return(errorValueFactory("[DROP AUTH ERROR] " + e.Message, IpcResultStatus.InvalidInput)); } catch (VssResourceNotFoundException e) { return(errorValueFactory("[DROP SERVICE ERROR] " + e.Message, IpcResultStatus.TransmissionError)); } catch (DropServiceException e) { var status = e.Message.Contains("already exists") ? IpcResultStatus.InvalidInput : IpcResultStatus.TransmissionError; return(errorValueFactory("[DROP SERVICE ERROR] " + e.Message, status)); } catch (DaemonException e) { return(errorValueFactory("[DAEMON ERROR] " + e.Message, IpcResultStatus.ExecutionError)); } }
public Engine(ILogger logger, ErrorFactory errorFactory) { _logger = logger; _errorFactory = errorFactory; }
internal async Task StartAsync(string configContent, RegistrationKind regKind) { Logger.LogInfo("Framework starting..."); // Load and validate configuration data var config = new Configuration(); config.Load(configContent); _config = config; var clientId = config.DefaultClientId; Organization = config.OAuth.Client.Organization; Name = config.OAuth.Client.ClientName; DetailedDescription = config.OAuth.Client.Description; Identifier = config.DefaultClientId.Id; Environment = config.DefaultClientId.Environment; RegisteredBy = config.DefaultClientId.RegisteredBy; Scope = new List <string>(config.DefaultClientId.Scope.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s))).AsReadOnly(); ScopeAsString = config.DefaultClientId.Scope; Status = config.DefaultClientId.Status; RedirectUri = config.DefaultClientId.RedirectUri; // Load device and any previous registration info. await MASDevice.InitializeAsync(config); // Authorization providers not supported yet //var response = await MAGRequests.GetAuthorizationProviders(_config, Device); // Load client access if client registration is requested if (MAS.RegistrationKind == RegistrationKind.Client) { Client = await MASUser.InitializeAsync(config, MASDevice.Current, true); } // Load user and any previous access token or idtoken info await MASUser.InitializeAsync(config, MASDevice.Current, false); if (!MASDevice.Current.IsRegistered) { switch (regKind) { case RegistrationKind.Client: if (!config.HasScope(ScopeNames.MssoClientRegister)) { ErrorFactory.ThrowError(ErrorCode.DeviceRegistrationAttemptedWithUnregisteredScope); } await MASDevice.Current.RegisterWithClientAsync(); // Create a device anonymous user var clientUser = new MASUser(_config, MASDevice.Current); await clientUser.LoginAnonymouslyAsync(); Client = clientUser; break; case RegistrationKind.User: // Ask for login with user device registration LoginRequested?.Invoke(null, EventArgs.Empty); break; default: ErrorFactory.ThrowError(ErrorCode.DeviceRegistrationAttemptedWithUnregisteredScope); break; } } Logger.LogInfo("Framework started"); }
private Engine() { this.errorFactory = new ErrorFactory(); }
public Negotiator CreateFailureResponse(string message, HttpStatusCode statusCode) { var error = ErrorFactory.CreateError <T>(message, statusCode); return(Negotiate.WithModel(error).WithStatusCode(statusCode)); }
protected Negotiator CreateFailureResponse(IEnumerable <string> messages, HttpStatusCode statusCode) { var error = ErrorFactory.CreateError <T>(messages, statusCode); return(Negotiate.WithModel(error).WithStatusCode(statusCode)); }
private object AccessOneByOne(object currentTarget, object previousTarget, List <Node> suffixes) { if (suffixes.Count == 0) { return(currentTarget); } if (currentTarget == null) { throw ErrorFactory.CreateNullError("Object"); } var currentSuffix = suffixes[0]; // bike function, .NET ctor or .NET delegate if (currentSuffix is Arguments) { var arguments = (Arguments)currentSuffix; // bike function if (currentTarget is BikeFunction) { previousTarget = CallBikeFunction((BikeFunction)currentTarget, previousTarget, arguments); } // ctor else if (currentTarget is Type) { var argValues = GetArgumentValues(arguments); previousTarget = CreateInstance((Type)currentTarget, argValues); } // delegate else { var args = GetArgumentValues(arguments); previousTarget = CallDelegate((Delegate)currentTarget, args); } return(AccessOneByOne(previousTarget, currentTarget, suffixes.ExceptFirst())); } if (currentSuffix is PropertyReferenceSuffix || currentSuffix is IndexSuffix || currentSuffix is TypeDescriptorSuffix) { if (currentTarget is BikeObject) { var currentSuffixStr = currentSuffix.SuffixValue(this); previousTarget = ((BikeObject)currentTarget).Resolve(currentSuffixStr); } else if (currentTarget is Type) // Static context { var currentSuffixStr = currentSuffix.SuffixValue(this); // Static generic call if (suffixes.Count > 2 && suffixes[1] is TypeDescriptorSuffix && suffixes[2] is Arguments ) { var typeParams = (Type[])suffixes[1].Accept(this); var args = GetArgumentValues((Arguments)suffixes[2]); previousTarget = CallStaticFunction((Type)currentTarget, typeParams, currentSuffixStr, args); suffixes = suffixes.ExceptFirst().ExceptFirst(); } // Static method or delegate else if (suffixes.Count > 1 && suffixes[1] is Arguments) { try { // delegate? previousTarget = GetStaticProperty((Type)currentTarget, currentSuffixStr); } catch (BikeObject bo) { if (!ErrorFactory.IsClrError(bo)) { throw; } // method? invoke immediately to avoid saving MethodInfo var args = GetArgumentValues((Arguments)suffixes[1]); previousTarget = CallStaticFunction((Type)currentTarget, currentSuffixStr, args); suffixes = suffixes.ExceptFirst(); } } else // .NET static property, invoke immediately { previousTarget = GetStaticProperty((Type)currentTarget, currentSuffixStr); } } // Must be .NET generic instance method else if (suffixes.Count > 2 && suffixes[1] is TypeDescriptorSuffix && suffixes[2] is Arguments) { var currentSuffixStr = currentSuffix.SuffixValue(this); var typeParams = (Type[])suffixes[1].Accept(this); var args = GetArgumentValues((Arguments)suffixes[2]); previousTarget = CallInstanceFunction(currentTarget, typeParams, currentSuffixStr, args); suffixes = suffixes.ExceptFirst().ExceptFirst(); } // .NET instance method or delegate else if (suffixes.Count > 1 && suffixes[1] is Arguments) { try { // delegate? var currentSuffixStr = currentSuffix.SuffixValue(this); previousTarget = GetInstanceProperty(currentTarget, currentSuffixStr); } catch (BikeObject bo) { if (!ErrorFactory.IsClrError(bo)) { throw; } // method? var currentSuffixStr = currentSuffix.SuffixValue(this); var args = GetArgumentValues((Arguments)suffixes[1]); previousTarget = CallInstanceFunction(currentTarget, currentSuffixStr, args); suffixes = suffixes.ExceptFirst(); } } // .NET instance property else if (currentSuffix is PropertyReferenceSuffix) { var currentSuffixStr = currentSuffix.SuffixValue(this); previousTarget = GetInstanceProperty(currentTarget, currentSuffixStr); } // .NET indexer else { previousTarget = GetInstanceIndexer(currentTarget, currentSuffix.Arguments(this)); } return(AccessOneByOne(previousTarget, currentTarget, suffixes.ExceptFirst())); } throw ErrorFactory.CreateError(string.Format("Invalid suffix type {0}", currentSuffix)); }
/// <summary> /// Convert escaped string until ' or " or { symbols /// </summary> /// <param name="rawString"></param> /// <param name="startPosition">open quote position</param> /// <returns>result: escaped string, resultPosition: index of closing quote symbol. -1 if no close quote symbol found</returns> public static (string result, int resultPosition) ReadQuotation(string rawString, int startPosition) { var sb = new StringBuilder(); int lastNonEscaped = startPosition + 1; int i = lastNonEscaped; var closeQuotationPosition = 0; for (; i < rawString.Length; i++) { var current = rawString[i]; if (current == '\'' || current == '"' || current == '{') { closeQuotationPosition = i; break; } if (rawString[i] != '\\') { continue; } if (lastNonEscaped != i) { var prev = rawString.Substring(lastNonEscaped, i - lastNonEscaped); sb.Append(prev); } if (i == rawString.Length - 1) { throw ErrorFactory.BackslashAtEndOfString(i, i + 1); } var next = rawString[i + 1]; char symbol; switch (next) { case '\\': symbol = '\\'; break; case 'n': symbol = '\n'; break; case 'r': symbol = '\r'; break; case '\'': symbol = '\''; break; case '"': symbol = '"'; break; case 't': symbol = '\t'; break; case 'f': symbol = '\f'; break; case 'v': symbol = '\v'; break; case '{': symbol = '{'; break; case '}': symbol = '}'; break; default: throw ErrorFactory.UnknownEscapeSequence(next.ToString(), i, i + 2); } sb.Append(symbol); i++; lastNonEscaped = i + 1; } if (closeQuotationPosition == 0) { return("", -1); } if (lastNonEscaped == startPosition + 1) { return(rawString.Substring(startPosition + 1, i - startPosition - 1), i); } if (lastNonEscaped <= rawString.Length - 1) { var prev = rawString.Substring(lastNonEscaped, i - lastNonEscaped); sb.Append(prev); } return(sb.ToString(), closeQuotationPosition); }
public Engine() { errorFactory = new ErrorFactory(); }
public Controller(IList <IAppender> appenders, AppenderFactory appenderFactory, ErrorFactory errorFactory) { this.appenders = appenders; this.appenderFactory = appenderFactory; this.errorFactory = errorFactory; }
public Engin(ILogger logger, ErrorFactory errorFactory) { this.logger = logger; this.errorFactory = errorFactory; }
public HttpResponseMessage ProcessTransaction(IncomingProcessTransaction model) { return(ErrorFactory.Handle(() => { var userId = User?.Identity?.GetUserId(); if (string.IsNullOrWhiteSpace(userId)) { throw new Exception(); } var context = new PoolReservationEntities(); using (var unitOfWork = new UnitOfWork(context)) { PrepareAndGetReservationForProcessing_Result reservation = null; try { reservation = context.PrepareAndGetReservationForProcessing(model.ReservationId)?.FirstOrDefault(); } catch (Exception) { context.ChangeProcessingStatusToPending(model.ReservationId); } if (reservation == null) { try { context.ChangeProcessingStatusToPending(model.ReservationId); } catch (Exception) { } return JsonFactory.CreateJsonMessage(null, HttpStatusCode.NotFound, this.Request); } if (reservation.StatusId != Convert.ToInt32(ReservationGroupStatusEnum.PROCESSING)) { try { context.ChangeProcessingStatusToPending(model.ReservationId); } catch (Exception) { } return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "wrongStatus" }, HttpStatusCode.NotFound, this.Request); } ReservationGroup reservationDBObject = null; try { reservationDBObject = unitOfWork.Reservations.GetReservationWithItems(userId, model.ReservationId); if (reservationDBObject == null) { return JsonFactory.CreateJsonMessage(null, HttpStatusCode.NotFound, this.Request); } } catch (Exception) { context.ChangeProcessingStatusToPending(model.ReservationId); } if (reservationDBObject.StatusId != Convert.ToInt32(ReservationGroupStatusEnum.PROCESSING)) { try { context.ChangeProcessingStatusToPending(model.ReservationId); } catch (Exception) { } return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "wrongStatus" }, HttpStatusCode.NotFound, this.Request); } ReservationTransaction resTransaction = null; int stripeModifiedPriceInCents = 0; try { decimal priceToCharge = 0M; foreach (var item in reservationDBObject.ReserveItems) { if (item.IsDeleted == true) { continue; } priceToCharge += item.FinalPrice; } decimal stripeModifiedPrice = priceToCharge * 100.0M; stripeModifiedPriceInCents = (int)Math.Round(stripeModifiedPrice); //Must Update Repo If Changed. Rounds to the nearest penny. if (stripeModifiedPriceInCents <= 50) { return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "noPriceToCharge" }, HttpStatusCode.NotFound, this.Request); } resTransaction = unitOfWork.Reservations.AddStripeChargeToPendingReservation(userId, userId, model.ReservationId, model.StripeTokenId, priceToCharge); unitOfWork.Complete(); } catch (Exception e) { context.ChangeProcessingStatusToPending(model.ReservationId); } string chargeId = null; try { if (resTransaction == null) { throw new Exception(); } var myCharge = new StripeChargeCreateOptions(); // always set these properties myCharge.Amount = stripeModifiedPriceInCents; myCharge.Currency = "usd"; // set this if you want to myCharge.Description = "JustMosey Reservation"; myCharge.SourceTokenOrExistingSourceId = model.StripeTokenId; // (not required) set this to false if you don't want to capture the charge yet - requires you call capture later myCharge.Capture = true; var chargeService = new StripeChargeService(); StripeCharge stripeCharge = chargeService.Create(myCharge); chargeId = stripeCharge.Id; unitOfWork.Reservations.UpdateStripeSuccessfulChargeOnPendingReservation(userId, userId, resTransaction.Id, chargeId); unitOfWork.Complete(); } catch (Exception e) { try { var refundService = new StripeRefundService(); StripeRefund refund = refundService.Create(chargeId, new StripeRefundCreateOptions() { Amount = stripeModifiedPriceInCents, Reason = StripeRefundReasons.Unknown }); } catch (Exception) { } try { unitOfWork.Reservations.RefundStripeSuccessfulChargeOnPendingReservation(userId, userId, resTransaction.Id); unitOfWork.Complete(); } catch (Exception) { } try { } catch (Exception) { context.ChangeProcessingStatusToPending(model.ReservationId); } return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "unknownErrorAfterProcessing" }, HttpStatusCode.InternalServerError, this.Request); } try { var updatedReservationDBObject = unitOfWork.Reservations.GetReservationWithItems(userId, model.ReservationId); var outgoingRes = OutgoingReservationGroup.Parse(updatedReservationDBObject); return JsonFactory.CreateJsonMessage(outgoingRes, HttpStatusCode.OK, this.Request); } catch (Exception) { return JsonFactory.CreateJsonMessage(null, HttpStatusCode.OK, this.Request); } } }, this.Request)); }
internal HttpContext(string controllerName) { _ControllerName = controllerName; _ErrorFactory = new ErrorFactory <HttpContext>(); }
public Engine() { this.errorFactory = new ErrorFactory(); }
public Word Visit(Graph graph) { var result = graph.FileName.Accept(this); if (IsError(result)) { return(ErrorFactory.GraphError(graph.FileName, "FileName", result)); } PyObj pyObjFileName; if (IsMemoryBlock(result))//comentar ese if else si se hace la desereferencia en atomic expr. { pyObjFileName = ((MemoryBlock)result).Value; } else { pyObjFileName = (PyObj)result; } if (pyObjFileName.GetMyType() != TypeConstants.STRING) { return(ErrorFactory.GraphError(graph.DotSource, "FileName", result)); } result = graph.DotSource.Accept(this); if (IsError(result)) { return(ErrorFactory.GraphError(graph.DotSource, "DotSource", result)); } PyObj pyObjDotSource; if (IsMemoryBlock(result))//comentar ese if else si se hace la desereferencia en atomic expr. { pyObjDotSource = ((MemoryBlock)result).Value; } else { pyObjDotSource = (PyObj)result; } if (pyObjDotSource.GetMyType() != TypeConstants.STRING) { return(ErrorFactory.GraphError(graph.DotSource, "DotSource", result)); } //Chapuz hacer un nuevo my string con el pyusac type porque graph solo recibe mystrings var path = ((MyString)pyObjFileName).StringValue; if (path.Length < 1) { return(ErrorFactory.PathNotValid(graph.FileName, path)); } if ((path[0] != Path.DirectorySeparatorChar) || (path[0] != 'C' && path[0] != 'D' && path[1] != ':'))//tiene que agregar al path la ruta del archivo con el que este nodo fue creado { path = graph.NodePath.GetParentPath() + Path.DirectorySeparatorChar + PyPath.ReplaceSepartors(path); } var pyPath = new PyPath(path); if (!Directory.Exists(pyPath.GetParentPath())) { return(ErrorFactory.PathNotValid(graph.FileName, pyPath.GetParentPath())); } var myStringPath = new MyString(path); var myStringDotSource = (MyString)pyObjDotSource; var environmentGraphResult = RuntimeEnvironment.Console.Instance.Graph(myStringPath, myStringDotSource); if (environmentGraphResult != null) { return(ErrorFactory.DotError(graph.DotSource, environmentGraphResult)); } return(null); }
public static IEnumerable <IEnumerable <CompositionError> > GetCompositionErrors() { foreach (var value in GetEmptyCollections <CompositionError>()) { yield return(value); } yield return(new CompositionError[] { new CompositionError("") }); yield return(new CompositionError[] { new CompositionError(""), new CompositionError("Description") }); yield return(new CompositionError[] { new CompositionError(""), new CompositionError("Description"), ErrorFactory.Create(CompositionErrorId.InvalidExportMetadata, "Description", (Exception)null), ErrorFactory.Create(CompositionErrorId.Unknown, "Description", new Exception()) }); }
public Word InvokeProcedure(ProcedureSegment procedureSegment) { var name = procedureSegment.Id; name = name.ToLowerInvariant(); var arguments = procedureSegment.Arguments; var argumentCount = arguments.Count; Procedure procedure; Procedures.TryGetValue(Procedure.EmptySignature(name, argumentCount), out procedure); if (procedure == null) { return(new MyError("No existe una funcion con el nombre: " + name + " y numero de parametros: " + argumentCount + " en las definiciones globales")); } //scope antes de llamar a la funcion var previousScope = CurrentScope; //Pasamos al scope global para llamar a la funcion CurrentScope = GlobalScope; ControlType controlType; if (procedure.GetDefinitionType() == DefinitionType.Function) { controlType = ControlType.Function; } else if (procedure.GetDefinitionType() == DefinitionType.Method) { controlType = ControlType.Method; } else { throw new Exception("definicion no valida. tiene que ser funciton o method"); } ControlStack.Push(controlType); //hacemos las declaraciones del metodo en un nuevo scope PushScope(); Word result; for (int i = 0; i < argumentCount; i++) { result = CurrentScope.Add(procedure.ParamNames[i], arguments[i]); if (IsError(result)) { ControlStack.Pop(); CurrentScope = previousScope; return(result); } } //Los stmt del metodo: foreach (var stmt in procedure.Stmts) { result = stmt.Accept(this); if (IsJumper(result)) { var jumper = (Jumper)result; if (!jumper.WasPopped() && !ControlStack.PopUntil(jumper)) { ErrorFactory.NotValidJumper(stmt, jumper); continue; } CurrentScope = previousScope; return(((Return)jumper).Obj); } } //Si termina de visitar los stmt, no entro jumper y es una funcion retorna MyNull y reporta un error ControlStack.Pop(); CurrentScope = previousScope; if (controlType == ControlType.Method) { return(null); } else { ErrorFactory.NoValueReturnedInFunction(procedure.Stmts.Last()); return(MyNull.GetInstance()); } }
public async Task <IServerMessage> GenerateResponse(IServerMessage request) { var orderDto = ParserFactory.GetDataParser(request.DataType).ParseData <OrderDto>(request.Body); var products = new List <Product>(); var stopWatch = new Stopwatch(); stopWatch.Start(); Parallel.ForEach(orderDto.Products.Select(x => x.Id).ToList(), (currentProductId) => { var unitOfWork = new UnitOfWork(); var product = unitOfWork.ProductRepository.GetOrDefault(currentProductId); if (product == null) { return; } lock (products) { products.Add(product); } }); stopWatch.Stop(); Console.WriteLine(stopWatch.Elapsed); if (products.Count < orderDto.Products.Count) { return(ErrorFactory.GetError(request.Message, 103, request.DataType)); } var itemsForfulfilment = new List <IItem>(); foreach (var product in products) { var bestItemPriority = -1; var availableItems = new UnitOfWork().ItemRepository.GetAvailableItemByProduct(product); var bestItem = availableItems.FirstOrDefault(); var itemLock = new object(); if (bestItem == null) { return(ErrorFactory.GetError(request.Message, 104, request.DataType)); } Parallel.ForEach(availableItems.Where(i => itemsForfulfilment.All(x => x.Id != i.Id)), (item) => { // This is executed in parallel because it may become the case in the future // that the algortihm that calculates the priority for a specifc product // is computationally expensive and as such this is a good candidate for // threading, although concurrently the gains are minimal if any! // It will also improve performance as the stock of a product grows // -- Strategy -- var itemPriority = product.Priority.CalculatePriority(item, product); lock (itemLock) { if (itemPriority > bestItemPriority) { bestItem = item; bestItemPriority = itemPriority; } } }); itemsForfulfilment.Add(bestItem); } // Now we need to make changes to the add them to the relevant sector and // update the state. Unit of work encapsulates all below operations var updateItems = new UnitOfWork(); foreach (var item in itemsForfulfilment) { item.State = ItemState.AwaitingPicker; item.QueuedTime = DateTime.Now; updateItems.ItemRepository.Update(item); } // Create the order and commit it to persistance var order = new Order() { Items = itemsForfulfilment, Status = OrderStatus.Recieved, ShippingAddress = orderDto.ShippingAddress }; updateItems.OrderRepository.Add(order); await updateItems.SaveChangesAsync(); // End of unit of work, changes have been saved // ------ // Lets inform the user that there order has been processed. We are going to use the // bridge in this case var customer = ParserFactory.GetDataParser(request.DataType).ParseData <Customer>(request.User); var communication = new UserCommunication() { Subject = "Order Update ", Endpoint = customer.Phone, Body = $" Hey {customer.Firstname}, your order has been placed successfully. Thanks for using Zeus Solutions." + $" Your order will be shipped to {orderDto.ShippingAddress}" }; // Use SMS to send order info - BRIDGE communication.CommunicationCommunicator = new SmsSender(); communication.Send(); return(new ServerMessage(request.Message + "Result", ParserFactory.GetDataParser(request.DataType).SerializeData(new OrderResultDto() { Success = true }))); }
public Word Visit(Declaration declaration) { var idList = new List <string>(); Word lResult; foreach (var lValue in declaration.LeftValues) { lResult = lValue.Accept(this); if (IsError(lResult)) { return(lResult); } idList.Add(((MyString)lResult).StringValue); } Word rValue; PyObj rPyObj; int i; if (declaration.Indexes.IsEmpty()) { if (declaration.RightValue == null) { rValue = MyNull.GetInstance(); } else { rValue = declaration.RightValue.Accept(this); } if (IsError(rValue)) { return(rValue); } if (IsMemoryBlock(rValue))//comentar ese if else si se hace la desereferencia en atomic expr. { rPyObj = ((MemoryBlock)rValue).Value; } else { rPyObj = (PyObj)rValue; } //rPyObj = (PyObj)rValue;//Descomentar esta linea si se hace la desereferencia en atomic expr. } else //Si tiene indices la declaracion significal que es un array { Word indexResult; PyObj indexPyObj; var intIndices = new int[declaration.Indexes.Count]; //Obtiene la lista de ints en sus indices. i = 0; foreach (var index in declaration.Indexes) { indexResult = index.Accept(this); if (IsError(indexResult)) { return(indexResult); } indexPyObj = ((IndexSegment)indexResult).Index; //Chequea que sea del tipo correcto: if (indexPyObj.GetMyType() == TypeConstants.INT) { intIndices[i] = ((MyInt)indexPyObj).Int; } else if (indexPyObj.GetMyType() == TypeConstants.CHAR) { intIndices[i] = ((MyChar)indexPyObj).CharValue; } else { return(ErrorFactory.ArrayDimensionError(index, indexPyObj)); } //Chequea que tenga un rango valido if (intIndices[i] < 0) { return(ErrorFactory.ArrayDimensionError(index, indexPyObj)); } i++; } if (declaration.RightValue == null) { rValue = MyArrayFactory.Create(intIndices); } else { rValue = declaration.RightValue.Accept(this); } if (IsError(rValue)) { return(rValue); } if (IsMemoryBlock(rValue))//comentar ese if else si se hace la desereferencia en atomic expr. { rPyObj = ((MemoryBlock)rValue).Value; } else { rPyObj = (PyObj)rValue; } //rPyObj = (PyObj)rValue;//Descomentar esta linea si se hace la desereferencia en atomic expr. //Verifica que rValue sea un array con las dimensiones especificadas en intIndices if (rPyObj.GetMyType() != TypeConstants.ARRAY) { return(ErrorFactory.ArrayTypeError(declaration, intIndices, rPyObj)); } if (!((MyArray)rPyObj).IsNDimensionalArray(intIndices)) { return(ErrorFactory.ArrayTypeError(declaration, intIndices, rPyObj)); } } Word result; i = 0;//Chapus minimo foreach (var id in idList) { result = CurrentScope.Add(id, rPyObj); if (IsError(result)) { ErrorFactory.Create(declaration.LeftValues[i], (MyError)result); } i++; } return(rPyObj);//Chapuz medio alto para facilitar el for }
private Engine() { errorFactory = new ErrorFactory(); }
public Word Visit(MemberAccess memberAccess) { var segmentResult = memberAccess.FirstSegment.Accept(this); if (IsError(segmentResult)) { return(segmentResult); } PyObj pyObj; var segment = (Segment)segmentResult; var segmentType = segment.GetSegmentType(); Word getSegmentResult; switch (segmentType) { case SegmentType.Identifier: { string id = ((IdentifierSegment)segment).Id; getSegmentResult = CurrentScope.Get(id); if (IsError(getSegmentResult)) //Revisa si esta entre las definiciones estaticas { getSegmentResult = StaticEntity.GetMember((IdentifierSegment)segment); if (IsError(getSegmentResult)) { return(ErrorFactory.Create(memberAccess.FirstSegment, (MyError)getSegmentResult)); } } pyObj = ((MemoryBlock)getSegmentResult).Value; } break; case SegmentType.Procedure: //pyObj en este caso es un pyObj o null (i.e. void) { getSegmentResult = InvokeProcedure((ProcedureSegment)segment); if (IsError(getSegmentResult)) //Revisa si esta entre las definiciones estaticas { getSegmentResult = StaticEntity.GetMember((ProcedureSegment)segment); if (IsError(getSegmentResult)) { return(ErrorFactory.Create(memberAccess.FirstSegment, (MyError)getSegmentResult)); } } pyObj = (PyObj)getSegmentResult; } break; case SegmentType.Expr: { getSegmentResult = ((ExprSegment)segment).Expr; if (IsError(getSegmentResult)) { return(getSegmentResult); } if (IsMemoryBlock(getSegmentResult)) //comentar ese if else si se hace la desereferencia en atomic expr. { pyObj = ((MemoryBlock)getSegmentResult).Value; } else { pyObj = (PyObj)getSegmentResult; } } break; default: throw new Exception("Tipo de segmento no reconocido: " + segmentType.ToString()); } MemberSegment memberSegment; foreach (var optionalSegment in memberAccess.OptionalSegments) { segmentResult = optionalSegment.Accept(this); if (IsError(segmentResult)) { return(segmentResult); } memberSegment = (MemberSegment)segmentResult; if (pyObj == null) { return(ErrorFactory.VoidGetMember(optionalSegment)); } getSegmentResult = pyObj.GetMember(memberSegment); if (IsError(getSegmentResult)) { return(ErrorFactory.Create(optionalSegment, (MyError)getSegmentResult)); } if (IsMemoryBlock(getSegmentResult)) { pyObj = ((MemoryBlock)getSegmentResult).Value; } else { pyObj = (PyObj)getSegmentResult; } } return(getSegmentResult); }
public Engine(ILogger logger, ErrorFactory factory) { this.logger = logger; this.errorFactory = factory; }
public Engine(ILogger logger) { this.logger = logger; this.errorFactory = new ErrorFactory(); }