Exemplo n.º 1
0
        public async Task <IHttpActionResult> Get(int?pageNumber = null, bool isAscending = false, string search = null)
        {
            try
            {
                Filter.PageNumber  = pageNumber ?? 1;
                Filter.Search      = search;
                Filter.IsAscending = isAscending;

                var pagedList = await VehicleMakeService.PagedList(Filter);

                var newModel = new
                {
                    Model       = pagedList.ToList(),
                    PageNumber  = pagedList.PageNumber,
                    PageSize    = pagedList.PageSize,
                    TotalCount  = pagedList.TotalItemCount,
                    isAscending = Filter.IsAscending
                };

                return(Ok(newModel));
            }
            catch (Exception ex)
            {
                LogError.LogError(ex);
                return(BadRequest(ex.Message));
            }
        }
        public void Visit(ProgramContext parserRule)
        {
            basicTypes = new BasicTypes(parserRule, globalContext);

            parserRule._classes.Insert(0, basicTypes.Int);
            parserRule._classes.Insert(0, basicTypes.Bool);
            parserRule._classes.Insert(0, basicTypes.String);
            parserRule._classes.Insert(0, basicTypes.IO);
            parserRule._classes.Insert(0, basicTypes.Void);
            parserRule._classes.Insert(0, basicTypes.Object);
            foreach (var _class in parserRule._classes)
            {
                if (globalContext.IfDefineType(_class.type.Text))
                {
                    errorLogger.LogError($"El programa ya contiene una definicion para { _class.type.Text}, linea {_class.type.Line} y la columna {_class.type.Column}");
                }
                else
                {
                    globalContext.CreateChildContext(_class.type.Text);
                    if (_class.inherits != null)
                    {
                        _class.father = parserRule._classes.FirstOrDefault(p => p.type.Text == _class.inherits.Text);
                    }
                    else if (_class.type.Text != "Object" && _class.type.Text != "void")
                    {
                        _class.father = basicTypes.Object;
                    }
                }
            }
            if (!globalContext.IfDefineType("Main"))
            {
                errorLogger.LogError("El programa no contiene la definicion para Main");
            }
        }
Exemplo n.º 3
0
        private FormatString ParseFormatString(int start)
        {
            var items = new List <FormatStringItem>();

            while (true)
            {
                switch (nextTokenInfo.Token)
                {
                case '{':
                    try
                    {
                        items.Add(ParseFormat());
                    }
                    catch (FormattingException e)
                    {
                        foreach (Error error in e.Errors)
                        {
                            errorLogger.LogError(error);
                        }

                        scanner.State = ScannerState.ScanningText;

                        while (nextTokenInfo.Token != '}' && nextTokenInfo.Token != Token.EndOfInput)
                        {
                            Consume();
                        }

                        break;
                    }

                    continue;

                case '}':
                    if (start > 0)
                    {
                        return(CreateFormatString(start, items));
                    }

                    errorLogger.LogError(nextTokenInfo.Location, "Unescaped \"}\".");
                    break;

                case Token.EndOfInput:
                    return(CreateFormatString(start, items));

                case Token.Text:
                    items.Add(new Text(nextTokenInfo.Location, nextTokenInfo.Text));
                    break;

                default:
                    // this should not happen
                    throw new InvalidOperationException(
                              Utilities.InvariantFormat("Token {0} is not valid here.", Token.ToString(nextTokenInfo.Token)));
                }

                Consume();
            }
        }
Exemplo n.º 4
0
        private void LogError(Uri baseUrl, IRestRequest request, IRestResponse response)
        {
            //Get the values of parameters passed to the API
            string parameters = string.Join(", ", request.Parameters.Select(x => x.Name.ToString()));

            //Setup the information message with the URL, the status code, and the parameters
            string info = "Request to " + BaseUrl.AbsoluteUri + request.Resource + " failed with status code " + response.StatusCode + ", parameters: "
                          + parameters + ", and content: " + response.Content;

            //Accquire the actual exception
            Exception ex;

            if (response != null && response.ErrorException != null)
            {
                ex = response.ErrorException;
            }
            else
            {
                ex   = new Exception(info);
                info = string.Empty;
            }

            //Log the exception and info messages
            _errorLogger.LogError(ex, info);
        }
Exemplo n.º 5
0
        public void LogTime(int hours, int minutes, string description)
        {
            try
            {
                //dobaviti podatke o trenutno logovanom korisniku (username, email)
                string userName  = userLogger.GetLoggedUserName();
                string userEmail = userLogger.GetLoggedUserEmail(userName);

                //dobaviti podatke o projektu i aktivnosti (task) na projektu za koju se loguje vreme
                int taskId = taskManager.GetTaskId(userName, userEmail);

                //logovati vreme - sacuvati podatke u bazi
                task.TaskId      = taskId;
                task.Hours       = hours;
                task.Minutes     = minutes;
                task.Description = description;
                bool saved = task.SaveToDB();
                if (saved)
                {
                    //poslati mejl obavestenja o logovanom vremenu
                    emailSender.SendEmail(userEmail,
                                          "Time logged successfully",
                                          hours + " hours and " + minutes + " minutes successfully logged to task with ID=" + taskId);
                }
                else
                {
                    throw new Exception("Failed to save data to database");
                }
            }
            catch (Exception ex) //obrada gresaka
            {
                errorLogger.LogError(ex);
                throw ex;
            }
        }
Exemplo n.º 6
0
        public Dictionary <Languages, LanguageDefinitions> LoadFiles()
        {
            Dictionary <Languages, LanguageDefinitions> result = new Dictionary <Languages, LanguageDefinitions>();

            foreach (Languages l in Enum.GetValues(typeof(Languages)))
            {
                string filename = GetFilename(l);
                string path     = Path.Combine(saveDirectory, filename);
                if (File.Exists(path))
                {
                    string contents = File.ReadAllText(path);
                    bool   loaded   = file.FromXML(contents);
                    if (loaded)
                    {
                        result[l] = new LanguageDefinitions(l, file.Data);
                    }
                }
                else
                {
                    errorLogger.LogError(new Error(ErrorCode.MissingLanguageFile, ErrorSeverity.Warning, path));
                }
            }

            return(result);
        }
Exemplo n.º 7
0
        public async Task <HostResult> CreateAsync(string userId, CreateHostRequest request)
        {
            var fileLocation = _setting.ScriptLocation;
            var currentHost  = _db.Hosts.FirstOrDefault(c => c.HostAddress == request.HostAddress);

            if (currentHost == null)
            {
                var hashCode = Guid.NewGuid().ToString();
                var newHost  = new Host()
                {
                    HostAddress = request.HostAddress, UserId = userId, HostValidated = true, PageValidated = false, HashCode = hashCode, UserValidityId = 9, ProductValidityId = 9
                };
                await _db.Hosts.AddAsync(newHost);

                await _db.SaveChangesAsync();

                await _db.UsersHostAccess.AddAsync(new UsersHostAccess()
                {
                    UserId = userId, AdminAccess = true, HostId = newHost.Id
                });

                await _db.SaveChangesAsync();

                try
                {
                    if (!System.IO.Directory.Exists(System.IO.Path.Combine(fileLocation, request.HostAddress.RemoveSpecialCharacters())))
                    {
                        System.IO.Directory.CreateDirectory(System.IO.Path.Combine(fileLocation, request.HostAddress.RemoveSpecialCharacters()));
                        System.IO.File.Copy(System.IO.Path.Combine(fileLocation, "track.js"), System.IO.Path.Combine(fileLocation, request.HostAddress.RemoveSpecialCharacters(), "track.js"));
                    }
                }
                catch (Exception ex)
                {
                    await _errorLogger.LogError("DashboardHostManager=>" + ex.Message);
                }
                return(new HostResult()
                {
                    Id = newHost.Id, TrackerAddress = _setting.ScriptAPIUrlBase + newHost.HostAddress.RemoveSpecialCharacters() + "/track.js", HostAddress = newHost.HostAddress
                });
            }
            else
            {
                return new HostResult()
                       {
                           Id                    = currentHost.Id,
                           TrackerAddress        = "https://api.stickytracker.net/" + currentHost.HostAddress.RemoveSpecialCharacters() + "/track.js",
                           HostAddress           = currentHost.HostAddress,
                           AlreadyExists         = true,
                           SegmentCreationAccess = new SegmentCreationAccess()
                           {
                               Page         = currentHost.HostValidated && currentHost.PageValidated,
                               AddToCart    = currentHost.AddToCardValidated,
                               Buy          = currentHost.FinalizeValidated,
                               ProductVisit = currentHost.CategoryValidated
                           }
                       }
            };
        }
Exemplo n.º 8
0
        private int ScanText()
        {
            do
            {
                char c = input[positionInInput++];

                switch (c)
                {
                case '{':
                case '}':
                    if (textBuilder.Length == 0)
                    {
                        textBuilder.Append(c);
                        return(c);
                    }

                    positionInInput--;
                    return(Token.Text);

                case '\\':
                    if (positionInInput == input.Length)
                    {
                        errorLogger.LogError(
                            new Location(positionInInput, positionInInput), "Unexpected end of input.");
                    }
                    else if (!Utilities.MustBeEscaped(c = input[positionInInput++]))
                    {
                        errorLogger.LogError(
                            new Location(positionInInput - 2, positionInInput),
                            Utilities.InvariantFormat("\"{0}\" cannot be escaped.", c));
                    }

                    break;
                }

                textBuilder.Append(c);
            }while(positionInInput < input.Length);

            return(Token.Text);
        }
Exemplo n.º 9
0
 public void Visit(ClassDef node)
 {
     currentType = Context.GetType(node.Type);
     if (node.typeInherited != null)
     {
         IType t;
         if ((t = Context.GetType(node.typeInherited)) != null)
         {
             currentType.TypeInherited = t;
             t.ChildTypes.Add(currentType);
         }
         else
         {
             errorLog.LogError(string.Format(TYPEINHERITEDDOESNEXIST, node.Line, currentType.Name, node.typeInherited));
         }
     }
     else
     {
         var obj = currentType.TypeInherited = Context.GetType("Object");
         obj.ChildTypes.Add(currentType);
     }
     foreach (var item in node.Attributes)
     {
         Visit(item);
     }
     foreach (var item in node.Methods)
     {
         Visit(item);
     }
     currentType.DefineAttribute("self", currentType);
 }
Exemplo n.º 10
0
        public IEnumerable <IRecord> FromString(string [] recordLines)
        {
            recordLines = recordLines.Where(x => !string.IsNullOrEmpty(x)).ToArray();

            if (recordLines == null || recordLines.Length == 0)
            {
                this.logger.LogError($"No record text provided");
                yield break;
            }
            var firstLine = recordLines.First();

            bool found = false;
            var  delim = ' ';

            foreach (var curDelimiter in allDelimiters)
            {
                if (firstLine.Contains(curDelimiter.ToString()))
                {
                    delim = curDelimiter;
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                logger.LogError("Text did not contain expected delimiters");
                yield break;
            }


            foreach (var curLine in recordLines)
            {
                Record ret      = new Record();
                var    curSplit = curLine.Split(delim);
                if (curSplit.Length != ExpectedLen)
                {
                    continue;
                }
                ret.LastName      = curSplit[LastNameIndex];
                ret.FirstName     = curSplit[FirstNameIndex];
                ret.Gender        = curSplit[GenderIndex];
                ret.FavoriteColor = curSplit[FavColorIndex];

                ret.DateOfBirth = ParseDate(curSplit[DOBIndex]);
                if (ret.DateOfBirth == null)
                {
                    yield break;
                }
                yield return(ret);
            }
        }
        private object GetValue(string propertyName, object fallBack)
        {
            string value = null;

            try
            {
                value = (string)Registry.GetValue(RegistryKey, propertyName, fallBack);
            }
            catch (Exception e)
            {
                Log.LogError(() => $"{nameof(RegeditReporterConfig)}.{nameof(GetValue)}({propertyName}, {fallBack}): " +
                             $"Call to Registry.GetValue({RegistryKey}, {propertyName}, {fallBack}) failed", e, ErrorCodes.FailedToReadRegistry);
            }

            return(string.IsNullOrWhiteSpace(value) ? fallBack : value);
        }
Exemplo n.º 12
0
        private void ParseEntry(TextReader reader, int lineNumber)
        {
            if (!reader.TryReadExpected("STR_"))
            {
                _logger.LogError(lineNumber, "Expected line to start with 'STR_'");
                return;
            }

            string identifier = reader.ReadString(4);

            string[] validIdentifiers = null;

            switch (_currentEntryType)
            {
            case LanguageEntryType.ObjectOverride:
                validIdentifiers = ObjectOverrideIdentifiers;
                break;

            case LanguageEntryType.ScenarioOverride:
                validIdentifiers = ScenarioOverrideIdentifiers;
                break;
            }

            if (validIdentifiers == null)
            {
                ushort index;
                if (!UInt16.TryParse(identifier, out index))
                {
                    _logger.LogError(lineNumber, $"String identifier must be between {UInt16.MinValue} and {UInt16.MaxValue}");
                    return;
                }
            }
            else
            {
                if (!validIdentifiers.Contains(identifier))
                {
                    _logger.LogError(lineNumber, $"Invalid identifier '{identifier}'");
                }
                if (!_groupItemIdentifiers.Add(identifier))
                {
                    _logger.LogWarning(lineNumber, $"Entry '{identifier}' already set.");
                }
            }

            ParseWhitespace(reader, lineNumber, 4);

            if (!reader.TryReadExpected(":"))
            {
                _logger.LogError(lineNumber, "Expected ':' after identifier");
            }

            string text = reader.ReadToEnd();
        }
Exemplo n.º 13
0
        protected override object DoVisit(ArgumentIndex argumentIndex)
        {
            if (argumentIndex.Index >= arguments.Count)
            {
                errorLogger.LogError(
                    argumentIndex.Location, Utilities.InvariantFormat("Argument index {0} is out of range.", argumentIndex.Index));

                return(Error);
            }

            return(arguments[argumentIndex.Index].Value);
        }
Exemplo n.º 14
0
        public void LogError(Uri baseURL, IRestRequest request, IRestResponse response)
        {
            string parameters = string.Join(", ", request.Parameters.Select(x => x.Name.ToString() + "=" + ((x.Value == null) ? "NULL" : x.Value)).ToArray());

            string info = "Request to " + baseURL.AbsoluteUri + request.Resource + " failed with status code " + response.StatusCode + ",  parameters: " + parameters + ",  and content: " + response.Content;

            Exception ex;

            if (response != null && response.ErrorException != null)
            {
                ex = response.ErrorException;
            }
            else
            {
                ex   = new Exception(info);
                info = String.Empty;
            }

            _errorLogger.LogError(ex, info);
        }
        protected async virtual Task ManageConsumersLoopAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                var queueInfo = CreateQueueInfo();

                lock (_scalingLock)
                {
                    _scalingAmount = _consumerCountManager.GetScalingAmount(queueInfo, _consumerWorkersCount);

                    for (var i = 1; i <= _scalingAmount; i++)
                    {
                        Task.Factory.StartNew(async() =>
                        {
                            try
                            {
                                Interlocked.Decrement(ref _scalingAmount);
                                Interlocked.Increment(ref _consumerWorkersCount);

                                using (IQueueConsumerWorker consumerWorker = CreateNewConsumerWorker())
                                {
                                    await consumerWorker.DoConsumeAsync(cancellationToken).ConfigureAwait(false);
                                }
                            }
                            catch (Exception exception)
                            {
                                Interlocked.Increment(ref _scalingAmount);
                                Interlocked.Decrement(ref _consumerWorkersCount);

                                _errorLogger?.LogError("RabbitMQ.AdvancedConsumer", exception.ToString(),
                                                       "QueueName", _queueName);
                            }
                        }, cancellationToken);
                    }
                }

                await Task.Delay(_consumerCountManager.AutoscaleFrequency, cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 16
0
        public void PlaceOrder(int orderId)
        {
            try
            {
                //dobaviti neophodne korisnicke podatke
                int    userId    = userLogger.GetLoggedUserId();
                string userEmail = userLogger.GetUserEmail(userId);

                //proveriti dostupnost proizvoda
                bool productAvailable = productChecker.CheckProductAvailability(orderId);

                //ukoliko su svi proizvodi dostupni skinuti proizvode sa stanja, sacuvati porudzbinu u bazi i poslati mejl potvrde
                if (productAvailable)
                {
                    stockManager.TakeOffStock(orderId);   //skidanje sa lagera
                    order.SaveOrderToDB(orderId, userId); //cuvanje porudzbine u bazi
                    emailSender.SendEmail(userEmail,
                                          "Order created successfully",
                                          "Your order was created successfully. You can use the orderId=" + orderId + " to track your order."); //slanje mejla potvrde
                }
                else
                {
                    throw new Exception("Some products are not available"); //neki proizvod nije dostupan
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("Some products are not available"))
                {
                    order.RemoveFromDB(orderId);      //porudzbina sa svim proizvodima se uklanja iz baze
                    stockManager.PutOnStock(orderId); //vracanje starog stanja na lageru
                }
                errorLogger.LogError(ex.Message);     //logovanje greske
                throw ex;
            }
        }
Exemplo n.º 17
0
        public static FunctionFormatTagParametersInfo ParseParameters(string key, IEnumerable <string> types, IEnumerable <ReswItem> basicLocalizedItems, string resourceFilename, IErrorLogger logger)
        {
            var result     = new FunctionFormatTagParametersInfo();
            var paramIndex = 1;

            foreach (var type in types)
            {
                var matchNamedParameters = RegexNamedParameters.Match(type.Trim());
                if (!matchNamedParameters.Success)
                {
                    logger?.LogError($"[ReswPlus] Incorrect tag for the key '{key}': incorrect formatting", resourceFilename);
                    return(null);
                }
                if (matchNamedParameters.Groups["literalString"].Success)
                {
                    var param = new LiteralStringFormatTagParameter()
                    {
                        Value = matchNamedParameters.Groups["literalString"].Value
                    };

                    result.Parameters.Add(param);
                }
                else
                {
                    if (matchNamedParameters.Groups["localizationRef"].Success)
                    {
                        var localizationRef = matchNamedParameters.Groups["localizationRef"].Value;
                        // Localization Identifier
                        if (!basicLocalizedItems.Any(i => i.Key == localizationRef))
                        {
                            //Identifier not found
                            logger?.LogError($"ReswPlus: Incorrect tag for the key '{key}': '{localizationRef}' doesn't exist in the resw file.", resourceFilename);
                            return(null);
                        }
                        var param = new StringRefFormatTagParameter()
                        {
                            Id = localizationRef
                        };

                        result.Parameters.Add(param);
                    }
                    else
                    {
                        var paramTypeId  = matchNamedParameters.Groups["type"].Value;
                        var isQuantifier = matchNamedParameters.Groups["quantifier"].Success;
                        var paramName    = matchNamedParameters.Groups["name"].Value;

                        if (isQuantifier && !string.IsNullOrEmpty(paramTypeId) && string.IsNullOrEmpty(paramName))
                        {
                            if (!AcceptedTypes.ContainsKey(paramTypeId))
                            {
                                paramName   = paramTypeId;
                                paramTypeId = "";
                            }
                        }
                        else if (!isQuantifier && paramTypeId == "Plural" && string.IsNullOrEmpty(paramName))
                        {
                            isQuantifier = true;
                            paramTypeId  = paramName = "";
                        }
                        else if (!isQuantifier && MacrosAvailable.TryGetValue(paramTypeId, out var macroID) && string.IsNullOrEmpty(paramName))
                        {
                            result.Parameters.Add(new MacroFormatTagParameter()
                            {
                                Id = macroID
                            });
                            continue;
                        }

                        var paramType = GetParameterType(paramTypeId, isQuantifier);
                        if (!paramType.type.HasValue)
                        {
                            logger?.LogError($"ReswPlus: Incorrect tag for the key '{key}': '{paramTypeId}' is not a correct type.", resourceFilename);
                            return(null);
                        }
                        if (string.IsNullOrEmpty(paramName))
                        {
                            if (paramTypeId == "Variant")
                            {
                                paramName = "variantId";
                            }
                            else if (isQuantifier)
                            {
                                paramName = "pluralCount";
                            }
                            else
                            {
                                paramName = "param" + paramType.type + paramIndex;
                            }
                        }

                        var functionParam = new FunctionFormatTagParameter {
                            Type = paramType.type.Value, Name = paramName, TypeToCast = paramType.typeToCast, IsVariantId = paramType.isVariantId
                        };
                        if (isQuantifier && result.PluralizationParameter == null)
                        {
                            result.PluralizationParameter = functionParam;
                        }
                        else if (paramTypeId == "Variant")
                        {
                            if (result.VariantParameter != null)
                            {
                                logger?.LogError($"ReswPlus: The key '{key}' has more than 1 Variant parameter", resourceFilename);
                                return(null);
                            }
                            result.VariantParameter = functionParam;
                        }
                        result.Parameters.Add(functionParam);
                        ++paramIndex;
                    }
                }
            }
            return(result);
        }
        public void Visit(MethodContext parserRuleContext)
        {
            //Creo un nuevo contexto dentro de metodos
            var context = new ObjectContext(type);

            //O_C[SELF_TYPE_type/self] defino la variable self con tipo SELF_TYPE_type
            context.Define("self", new SelfType(type, globalContext));
            foreach (var formal in parserRuleContext._formals)
            {
                Visit(formal, context);
            }
            //Porque los tipo IO y Object no tienen implementacion
            if (type == globalContext.IO || type == globalContext.Object || type == globalContext.Int || type == globalContext.String)
            {
                return;
            }
            //Visito el cuerpo del metodo
            Visit(parserRuleContext.exprBody, context);
            var typeMethod = globalContext.GetType(parserRuleContext.TypeReturn.Text, type);

            //si al menos un tipo es undefined no se reporta error plq la expresion es null
            //Alomejor hay que especificar el nombre del metodo en el error
            if (!parserRuleContext.exprBody.computedType.Conform(typeMethod))
            {
                errorLogger.LogError($"({parserRuleContext.Start.Line},{parserRuleContext.Start.Column+1}) - Type Error : In the method {parserRuleContext.idText} of class {type.Name} the type of the method body {parserRuleContext.exprBody.computedType.Name} not conform to the declared return type {typeMethod.Name}");
            }
        }
Exemplo n.º 19
0
        public async Task <string> UpdateProducts([FromBody] ProductLog logData)
        {
            try
            {
                var fiProducts = logData.ProductData.OrderByDescending(c => c.ProductId).Take(20);
                var host       = await _hostCache.GetHostByIdAsync(logData.HostId).ConfigureAwait(false);

                if (host == null || host.Id == 0)
                {
                    return(CommonStrings.NoHost);
                }
                #region SecurityCheck
                if (_configurations.SecurityCheck)
                {
                    var origin = Request.Headers[CommonStrings.Origin].ToString();
                    if (!string.IsNullOrEmpty(origin))
                    {
                        var aut = new Uri(origin).Host;
                        aut = aut.ToLower();
                        var topdomain = string.Empty;
                        if (aut.IndexOf(CommonStrings.Dot) == aut.LastIndexOf(CommonStrings.Dot))
                        {
                            topdomain = aut;
                        }
                        else
                        {
                            topdomain = aut.Substring(aut.IndexOf(CommonStrings.Dot) + 1);
                        }
                        if (host.Host != topdomain)
                        {
                            return(CommonStrings.NoHostAccess);
                        }
                    }
                }
                #endregion
                if (logData != null && (await _crowlerCache.IsCrowler(logData.UserId)))
                {
                    return(string.Empty);
                }
                List <Task> tasks = new List <Task>
                {
                    _totalVisitUpdater.UpdateTotalVisit(logData.HostId)
                };
                await _hostScriptChecker.UpdateProductValidation(logData.HostId);

                var categoriesforlog = logData.ProductData.Where(c => !string.IsNullOrEmpty(c.Category)).GroupBy(c => c.Category).Select(v => new KeyValuePair <string, int>(v.Key, v.Count()));
                foreach (var category in categoriesforlog)
                {
                    tasks.Add(_categoryLogger.LogCategory(host.Id, category.Key, category.Value));
                }
                foreach (var item in fiProducts)
                {
                    var updateedProduct = new HostProduct()
                    {
                        Description  = item.Description,
                        ImageAddress = item.ImageAddress,
                        IsAvailable  = item.Available,
                        Price        = item.Price,
                        Url          = item.PageAddress,
                        Id           = item.ProductId,
                        ProductName  = item.Name,
                        CategoryName = item.Category,
                        UpdateDate   = DateTime.Now
                    };
                    tasks.Add(_productCache.UpdateProduct(logData.HostId, updateedProduct));
                }

                #region Log Into Kafka
                foreach (var item in logData.ProductData)
                {
                    await _kafkaLogger.SendMessage(new DruidData()
                    {
                        CategoryName = item.Category,
                        Date         = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"),
                        HostName     = host.Host,
                        ImageAddress = item.ImageAddress,
                        Price        = item.Price,
                        ProductName  = item.Name,
                        PageAddress  = item.PageAddress,
                        ProductId    = item.ProductId,
                        StatType     = StatTypes.ProductView,
                        UserId       = logData.UserId.ToString(),
                        HostId       = logData.HostId.ToString(),
                    });
                }
                #endregion

                await Task.WhenAll(tasks).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await _errorLogger.LogError("Operation:ProductUpdate =>" + ex.Message);
            }
            return(string.Empty);
        }
Exemplo n.º 20
0
        public void Visit(New node)
        {
            var type = Context.GetType(node.Type);

            if (type == null)
            {
                errorLog.LogError(string.Format(TypeNotExist, node.Line, node.Type));
                node.computedType = Context.GetType("Void");
            }
            else
            {
                node.computedType = type;
            }
        }
Exemplo n.º 21
0
        public async Task <string> LogUser([FromBody] PageLogRequest pageData)
        {
            try
            {
                var innerAddress = new Uri(pageData.Address).PathAndQuery;
                var host         = await _hostCache.GetHostByIdAsync(pageData.HostId);

                if (host == null || host.Id == 0)
                {
                    return(CommonStrings.NoHost);
                }
                #region SecurityCheck
                if (_configurations.SecurityCheck)
                {
                    var origin = Request.Headers[CommonStrings.Origin].ToString();
                    if (!string.IsNullOrEmpty(origin))
                    {
                        var aut = new Uri(origin).Host;
                        aut = aut.ToLower();
                        var topdomain = string.Empty;
                        if (aut.IndexOf(CommonStrings.Dot) == aut.LastIndexOf(CommonStrings.Dot))
                        {
                            topdomain = aut;
                        }
                        else
                        {
                            topdomain = aut.Substring(aut.IndexOf(CommonStrings.Dot) + 1);
                        }
                        if (host.Host != topdomain)
                        {
                            return(CommonStrings.NoHostAccess);
                        }
                    }
                }
                #endregion

                if (pageData != null && (await _crowlerCache.IsCrowler(pageData.UserId)))
                {
                    return("");
                }
                await _totalVisitUpdater.UpdateTotalVisit(pageData.HostId);

                await _hostScriptChecker.UpdatePageValidation(pageData.HostId);

                await _kafkaLogger.SendMessage(new DruidData()
                {
                    CategoryName = "",
                    Date         = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"),
                    HostName     = host.Host,
                    ImageAddress = "",
                    Price        = 0,
                    ProductName  = "",
                    PageAddress  = innerAddress,
                    ProductId    = "",
                    StatType     = StatTypes.PageView,
                    UserId       = pageData.UserId.ToString(),
                    HostId       = pageData.HostId.ToString(),
                });
            }
            catch (Exception ex)
            {
                await _errorLogger.LogError("Operation:PageLogger =>" + "User=>" + pageData.UserId + ":" + ex.Message);
            }
            return("");
        }
Exemplo n.º 22
0
        public async Task UpdateProducts([FromBody] RemoveProductLog logData)
        {
            try
            {
                var productIds     = logData.ProductData.Select(c => c.ProductId);
                var productAddress = new Uri(logData.PageAddress).PathAndQuery;
                var host           = await _hostDictionary.GetHostByIdAsync(logData.HostId);

                if (host == null || host.Id == 0)
                {
                    return;
                }
                #region SecurityCheck
                if (_configurations.SecurityCheck)
                {
                    var origin = Request.Headers[CommonStrings.Origin].ToString();
                    if (!string.IsNullOrEmpty(origin))
                    {
                        var aut = new Uri(origin).Host;
                        aut = aut.ToLower();
                        var topdomain = string.Empty;
                        if (aut.IndexOf(CommonStrings.Dot) == aut.LastIndexOf(CommonStrings.Dot))
                        {
                            topdomain = aut;
                        }
                        else
                        {
                            topdomain = aut.Substring(aut.IndexOf(CommonStrings.Dot) + 1);
                        }
                        if (host.Host != topdomain)
                        {
                            return;
                        }
                    }
                }
                #endregion
                await _hostScriptChecker.UpdateBuyValidation(logData.HostId);

                foreach (var item in productIds)
                {
                    var cachedProduct = await _productCache.FindProduct(logData.HostId, item);

                    if (cachedProduct.Id != string.Empty)
                    {
                        await _kafkaLogger.SendMessage(new DruidData()
                        {
                            CategoryName = cachedProduct.CategoryName,
                            Date         = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"),
                            HostName     = host.Host,
                            ImageAddress = cachedProduct.ImageAddress,
                            Price        = cachedProduct.Price,
                            ProductName  = cachedProduct.ProductName,
                            PageAddress  = cachedProduct.Url,
                            ProductId    = item,
                            StatType     = StatTypes.ProductPurchase,
                            UserId       = logData.UserId.ToString(),
                            HostId       = logData.HostId.ToString(),
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                await _errorLogger.LogError("Operation:Buy =>" + ex.Message);
            }
        }
Exemplo n.º 23
0
        private StronglyTypedClass Parse(string content, string defaultNamespace, bool isAdvanced)
        {
            var namespaceToUse   = ExtractNamespace(defaultNamespace);
            var resourceFileName = Path.GetFileName(_resourceFileInfo.Path);
            var className        = Path.GetFileNameWithoutExtension(_resourceFileInfo.Path);
            var reswInfo         = ReswParser.Parse(content);

            var projectNameIfLibrary = _resourceFileInfo.ParentProject.IsLibrary ? _resourceFileInfo.ParentProject.Name : null;

            //If the resource file is in a library, the resource id in the .pri file
            //will be <library name>/FilenameWithoutExtension
            var resouceNameForResourceLoader = string.IsNullOrEmpty(projectNameIfLibrary) ?
                                               className : projectNameIfLibrary + "/" + className;


            var result = new StronglyTypedClass()
            {
                IsAdvanced  = isAdvanced,
                ClassName   = className,
                Namespaces  = namespaceToUse,
                ResoureFile = resouceNameForResourceLoader
            };

            var stringItems = reswInfo.Items
                              .Where(i => !i.Key.Contains(".") && !(i.Comment?.Contains(TagIgnore) ?? false)).ToArray();

            if (isAdvanced)
            {
                //check Pluralization
                var itemsWithPluralOrVariant = reswInfo.Items.GetItemsWithVariantOrPlural();
                var basicItems = stringItems.Except(itemsWithPluralOrVariant.SelectMany(e => e.Items)).ToArray();

                foreach (var item in itemsWithPluralOrVariant)
                {
                    if (item.SupportPlural)
                    {
                        var idNone      = item.Key + "_None";
                        var hasNoneForm = reswInfo.Items.Any(i => i.Key == idNone);

                        var singleLineValue = _regexRemoveSpace.Replace(item.Items.FirstOrDefault().Value, " ").Trim();

                        var summary = $"Get the pluralized version of the string similar to: {singleLineValue}";

                        PluralLocalization localization;
                        if (item.SupportVariants)
                        {
                            localization = new PluralVariantLocalization()
                            {
                                Key              = item.Key,
                                Summary          = summary,
                                SupportNoneState = hasNoneForm,
                            };
                        }
                        else
                        {
                            localization = new PluralLocalization()
                            {
                                Key              = item.Key,
                                Summary          = summary,
                                SupportNoneState = hasNoneForm,
                            };
                        }
                        if (item.Items.Any(i => i.Comment != null && i.Comment.Contains(Deprecated_TagStrongType)))
                        {
                            _logger?.LogError($"{Deprecated_TagStrongType} is no more supported, use {TagFormat} instead. See https://github.com/rudyhuyn/ReswPlus/blob/master/README.md");
                        }
                        var commentToUse =
                            item.Items.FirstOrDefault(i => i.Comment != null && _regexStringFormat.IsMatch(i.Comment));

                        ManageFormattedFunction(localization, commentToUse?.Comment, basicItems, resourceFileName);

                        result.Localizations.Add(localization);
                    }
                    else if (item.SupportVariants)
                    {
                        var singleLineValue = _regexRemoveSpace.Replace(item.Items.FirstOrDefault().Value, " ").Trim();
                        var summary         = $"Get the variant version of the string similar to: {singleLineValue}";
                        var commentToUse    = item.Items.FirstOrDefault(i => i.Comment != null && _regexStringFormat.IsMatch(i.Comment));

                        var localization = new VariantLocalization()
                        {
                            Key     = item.Key,
                            Summary = summary,
                        };

                        ManageFormattedFunction(localization, commentToUse?.Comment, basicItems, resourceFileName);

                        result.Localizations.Add(localization);
                    }
                }

                stringItems = basicItems;
            }

            if (stringItems.Any())
            {
                foreach (var item in stringItems)
                {
                    var singleLineValue = _regexRemoveSpace.Replace(item.Value, " ").Trim();
                    var summary         = $"Looks up a localized string similar to: {singleLineValue}";

                    var localization = new RegularLocalization()
                    {
                        Key     = item.Key,
                        Summary = summary,
                    };

                    if (isAdvanced)
                    {
                        ManageFormattedFunction(localization, item.Comment, stringItems, resourceFileName);
                    }
                    result.Localizations.Add(localization);
                }
            }

            return(result);
        }
 public void Visit(ClassContext parserRule)
 {
     type = globalContext.GetType(parserRule.type.Text);
     if (parserRule.inherits != null)
     {
         if (!globalContext.IfDefineType(parserRule.inherits.Text))
         {
             errorLogger.LogError($"El tipo con nombre {parserRule.inherits.Text} no ha sido encontrado");
         }
         if (globalContext.Int.Name == parserRule.inherits.Text)
         {
             errorLogger.LogError($"El tipo {parserRule.type.Text} no puede heredar de Int");
         }
         if (globalContext.String.Name == parserRule.inherits.Text)
         {
             errorLogger.LogError($"El tipo {parserRule.type.Text} no puede heredar de String");
         }
         if (globalContext.Bool.Name == parserRule.inherits.Text)
         {
             errorLogger.LogError($"El tipo {parserRule.type.Text} no puede heredar de Bool");
         }
         var inherits = globalContext.GetType(parserRule.inherits.Text);
         type.Inherits = inherits;
         if (inherits.Conform(type))
         {
             errorLogger.LogError("No se permite la herencia cíclica");
         }
     }
     foreach (var item in parserRule._features)
     {
         Visit(item);
     }
     //Verifico si la clase Main tiene el metodo main y si este no tiene parametros
     if (parserRule.type.Text == "Main")
     {
         if (type.IsDefineMethod("main"))
         {
             var main = type.GetMethod("main");
             if (main.Formals.Length > 0)
             {
                 errorLogger.LogError("El metodo main no tiene parametros");
             }
         }
         else
         {
             errorLogger.LogError("El metodo main no esta definido en la clase Main");
         }
     }
 }
Exemplo n.º 25
0
        public async Task <string> UpdateProducts([FromBody] AddToCartLog logData)
        {
            try
            {
                var host = await _hostCache.GetHostByIdAsync(logData.HostId);

                if (host == null || host.Id == 0)
                {
                    return(CommonStrings.NoHost);
                }
                #region SecurityCheck
                if (_configurations.SecurityCheck)
                {
                    var origin = Request.Headers[CommonStrings.Origin].ToString();
                    if (!string.IsNullOrEmpty(origin))
                    {
                        var aut = new Uri(origin).Host;
                        aut = aut.ToLower();
                        var topdomain = string.Empty;
                        if (aut.IndexOf(CommonStrings.Dot) == aut.LastIndexOf(CommonStrings.Dot))
                        {
                            topdomain = aut;
                        }
                        else
                        {
                            topdomain = aut.Substring(aut.IndexOf(CommonStrings.Dot) + 1);
                        }
                        if (host.Host != topdomain)
                        {
                            return(CommonStrings.NoHostAccess);
                        }
                    }
                }
                #endregion

                var productad = logData.ProductData.OrderByDescending(c => c.ProductId).ToList();
                if (!productad.Any())
                {
                    return(string.Empty);
                }
                await _hostScriptChecker.UpdateCartValidation(logData.HostId);

                await _totalVisitUpdater.UpdateTotalVisit(logData.HostId);

                foreach (var item in productad)
                {
                    var cachedProduct = await _productCache.FindProduct(logData.HostId, item.ProductId);

                    if (cachedProduct.Id != string.Empty)
                    {
                        await _kafkaLogger.SendMessage(new DruidData()
                        {
                            CategoryName = cachedProduct.CategoryName,
                            Date         = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"),
                            HostName     = host.Host,
                            ImageAddress = cachedProduct.ImageAddress,
                            Price        = cachedProduct.Price,
                            ProductName  = cachedProduct.ProductName,
                            PageAddress  = cachedProduct.Url,
                            ProductId    = item.ProductId,
                            StatType     = StatTypes.AddToCart,
                            UserId       = logData.UserId.ToString(),
                            HostId       = logData.HostId.ToString(),
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                await _errorLogger.LogError("Operations:AdToCart->" + ex.Message);
            }



            return("");
        }
Exemplo n.º 26
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/html";
                var requestHost = context.Request.Headers["Referer"];
                if (string.IsNullOrEmpty(requestHost))
                {
                    await context.Response.WriteAsync("No Iframe! Don't Cheat!");

                    return;
                }
                string host      = new Uri(requestHost).Authority.ToString();
                var    topdomain = "";
                if (host.IndexOf(".") == host.LastIndexOf("."))
                {
                    topdomain = host;
                }
                else
                {
                    topdomain = host.Substring(host.IndexOf(".") + 1);
                }
                var hostData = await _hostCache.GetHostAsync(topdomain);

                if (hostData == null)
                {
                    return;
                }

                string userCookie = context.Request.Cookies[_configuration.CookieName];
                //try
                //{
                //    var logAgent= _redisCache.GetDatabase(DataAccess.RedisDatabases.CacheData).StringGet("LogAgent");
                //    if (logAgent.HasValue)
                //    {
                //    var userAgent = context.Request.Headers["User-Agent"].ToString();
                //    var agentstring = string.IsNullOrEmpty(userAgent.ToString()) ? "unknown" : userAgent.ToString();
                //    var agentDb = _redisCache.GetDatabase(DataAccess.RedisDatabases.Logs);
                //    await agentDb.HashIncrementAsync("AgentCounter",agentstring);
                //    }

                //}
                //catch
                //{

                //}

                long userId = 0;
                if (userCookie == null)
                {
                    userId = await _userIdSetter.GetNewUserIdAsync();

                    var co = new CookieOptions()
                    {
                        Expires  = DateTime.Now.AddYears(5),
                        SameSite = SameSiteMode.None
                    };
                    if (_configuration.CookieDomain != ".")
                    {
                        co.Domain = _configuration.CookieDomain;
                    }
                    context.Response.Cookies.Append(_configuration.CookieName, userId.ToString(), co);
                }
                else
                {
                    var resultofparseCookie = long.TryParse(userCookie, out userId);
                    if (!resultofparseCookie)
                    {
                        return;
                    }
                }
                if (await _crowlerCache.IsCrowler(userId))
                {
                    return;
                }
                var rawhtml  = "<!DOCTYPE html><html><head><meta charset=\"utf-8\" /><title></title></head><body>partner_iframes<script>var sendingData = {};sendingData.message = \"GetCookie\";sendingData.UserId = user_identity;sendingData.FinalizePage = 'finalize_page';sendingData.HostId = host_identity;sendingData.AddToCart = 'add_to_cart';parent.postMessage(JSON.stringify(sendingData), \"*\");</script></body></html>";
                var html     = rawhtml.Replace("user_identity", userId.ToString()).Replace("host_identity", hostData.Id.ToString()).Replace("add_to_cart", hostData.AddToCardId).Replace("finalize_page", hostData.FinalizePage);
                var partners = await _partnerCache.ListAsync();

                var pixelHtml = "";
                foreach (var item in partners)
                {
                    if (!string.IsNullOrEmpty(item.CookieSyncAddress))
                    {
                        var partnerAddress = item.CookieSyncAddress?.Replace("@StickyId", userId.ToString());
                        pixelHtml += "<iframe src=\"" + partnerAddress + "\"></iframe>";
                    }
                }
                html = html.Replace("partner_iframes", pixelHtml);
                await context.Response.WriteAsync(html);
            }
            catch (Exception ex)
            {
                await _errorLogger.LogError(ex.Message);
            }
        }