示例#1
0
        /// <summary>
        /// Zapisywanie uprawnień do bazy danych
        /// </summary>
        /// <param name="device">Nośnik</param>
        /// <returns>Odpowiedź o stanie zapisu</returns>
        public ApiResponse Save(Device device)
        {
            var response = new ApiResponse();

            try
            {
                if (device.Id == 0)
                {
                    dynamic dbEntry = new Device();

                    dbEntry.Name   = device.Name;
                    dbEntry.UserId = device.UserId;
                    dbEntry.TypeId = device.TypeId;
                    SetRelation(device, ref dbEntry);
                    dbEntry.Description = device.Description;
                    Context.Devices.Add(dbEntry);
                }
                else
                {
                    dynamic dbEntry = Context.Devices.Find(device.Id);
                    if (dbEntry != null)
                    {
                        SetRelation(device, ref dbEntry);

                        dbEntry.Name        = device.Name;
                        dbEntry.TypeId      = device.TypeId;
                        dbEntry.Statistics  = device.Statistics;
                        dbEntry.UserId      = device.UserId;
                        dbEntry.Description = device.Description;
                    }
                }

                Context.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                // Obsługa błędów EF
                using (var handler = new DbValidationErrorHandler(ex))
                {
                    if (handler.HasErrors)
                    {
                        response.Errors.AddRange(handler.ValidationErrors);
                    }
                }
            }
            catch (Exception ex)
            {
                var hierarchy = new List <Exception>();
                ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                if (hierarchy.Count > 0)
                {
                    response.Errors.AddRange(hierarchy.Select(s => new ApiValidationErrorItem {
                        Message = s.Message
                    }).Distinct().AsEnumerable());
                }
            }

            response.Accepted = response.Errors.Count == 0;
            return(response);
        }
示例#2
0
        /// <summary>
        /// Serializacja odpowiedzi
        /// </summary>
        /// <param name="response">Informacje do serializacji</param>
        /// <param name="errors">Lista dotychczasowych błędów</param>
        private string SerializeResponse(GetMultimediaObject_Response response, List <string> errors)
        {
            string result;

            try
            {
                // Przypisz listę błędów do obiektu
                response.ErrorsOccured = errors != null && errors.Count > 0;
                response.ErrorMessage  = new List <string>();

                if (errors != null && errors.Count > 0)
                {
                    response.ErrorMessage.AddRange(errors);
                }

                // Serializuj obiekt
                result = JsonConvert.SerializeObject(response);
            }

            // Serializacja nie powiodła się
            catch (Exception ex)
            {
                // Zaloguj wyjątek do pliku logów
                SaveErrorInLogFile(ex);

                // Wyczyść obiekt
                response = new GetMultimediaObject_Response();

                // Wyczyść dotychczasowe błędy
                errors = new List <string>();

                // Pobierz aktualne błędy
                var hierarchy = new List <Exception>();
                ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                if (hierarchy.Count > 0)
                {
                    errors.AddRange(hierarchy.Select(s => s.Message + Environment.NewLine + s.StackTrace).Distinct().AsEnumerable());
                }

                response.ErrorsOccured = errors.Count > 0;
                response.ErrorMessage  = new List <string>();
                if (errors.Count > 0)
                {
                    response.ErrorMessage.AddRange(errors);
                }

                // Ponowna serializacja
                result = JsonConvert.SerializeObject(response);
            }

            return(result);
        }
示例#3
0
        /// <summary>
        /// Zapisywanie typu do bazy danych
        /// </summary>
        /// <param name="type">Obiekt typu</param>
        public ApiResponse Save(Models.Type type)
        {
            var response = new ApiResponse();

            try
            {
                if (type.Id == 0)
                {
                    Context.Types.Add(type);
                }
                else
                {
                    var dbEntry = Context.Types.Find(type.Id);
                    if (dbEntry != null)
                    {
                        dbEntry.Name   = type.Name;
                        dbEntry.Height = type.Height;
                        dbEntry.Width  = type.Width;
                    }
                }

                Context.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                //  Obsługa błędów EF
                using (var handler = new DbValidationErrorHandler(ex))
                {
                    if (handler.HasErrors)
                    {
                        response.Errors.AddRange(handler.ValidationErrors);
                    }
                }
            }
            catch (Exception ex)
            {
                var hierarchy = new List <Exception>();
                ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                if (hierarchy.Count > 0)
                {
                    response.Errors.AddRange(hierarchy.Select(s => new ApiValidationErrorItem {
                        Message = s.Message
                    }).Distinct().AsEnumerable());
                }
            }

            response.Accepted = response.Errors.Count == 0;
            return(response);
        }
示例#4
0
        public void Dispose()
        {
            if (_tcpClient.Connected)
            {
                ExceptionsHandlingHelper.ExecuteWithExceptionLogging(
                    () => SendData(_networkStream, NetworkConstants.EndOfSessionMessageBytes),
                    () =>
                {
                    _tcpClient.Close();
                    _networkStream.Dispose();
                },
                    _logger);
            }

            _tcpClient.Dispose();
        }
示例#5
0
        private async Task CloseTcpClient(TcpClientHolder tcpClientHolder)
        {
            if (tcpClientHolder.TcpClient.Connected)
            {
                await ExceptionsHandlingHelper.ExecuteWithExceptionLogging(
                    () => SendDataAsync(
                        tcpClientHolder.NetworkStream,
                        NetworkConstants.EndOfSessionMessageBytes),
                    async() =>
                {
                    // ReSharper disable once AccessToDisposedClosure - synchronous code
                    tcpClientHolder.TcpClient.Close();
                    await tcpClientHolder.NetworkStream.DisposeAsync();
                },
                    _logger);
            }

            tcpClientHolder.TcpClient.Dispose();
        }
        /// <summary>
        /// Zebranie informacji do zalgowania
        /// </summary>
        /// <param name="ex">Wyjątek</param>
        /// <param name="logPath">Ścieżka do katalogu logów</param>
        /// <param name="filterContext">Kontekst wyjątku</param>
        /// <param name="primaryMessage">Główny komunikat błędu</param>
        private string LogException(Exception ex, string logPath, ExceptionContext filterContext, out string primaryMessage)
        {
            List <Exception> hierarchy = new List <Exception>();

            primaryMessage = string.Empty;

            ///Obsługa błędów bazodanowych
            if (ex is System.Data.Entity.Validation.DbEntityValidationException)
            {
                ///Pobranie informacji o błędach EF
                using (DbValidationErrorHandler dbValExp = new DbValidationErrorHandler(ex as System.Data.Entity.Validation.DbEntityValidationException))
                {
                    if (dbValExp.HasErrors)
                    {
                        foreach (var exp in dbValExp.ValidationErrors)
                        {
                            hierarchy.Add(new Exception(exp.Message));
                        }

                        primaryMessage = string.Join(Environment.NewLine, dbValExp.ValidationErrors.Select(s => s.Message).ToArray());
                    }
                    else
                    {
                        primaryMessage = ex.Message;
                        ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                    }
                }
            }

            ///Obsługa zwykłych błędów
            else
            {
                primaryMessage = ex.Message;
                ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
            }
            string destinationPath = logPath;

            return(LogToFile(ref hierarchy, destinationPath, null, filterContext));
        }
示例#7
0
        /// <summary>
        /// Zapisuje do pliku informację o wyjątku
        /// </summary>
        /// <param name="selectionParams">Parametry requesta</param>
        /// <param name="ex">Obiekt wyjątku</param>
        private static void SaveErrorInLogFile(MultimediaObjectSelection.MultimediaObjectsSelectionParams selectionParams, Exception ex)
        {
            try
            {
                if (selectionParams == null || ex == null)
                {
                    return;
                }

                var exceptions = new List <Exception>();
                ExceptionsHandlingHelper.HierarchizeError(ex, ref exceptions);

                var message = string.Format("{3}Exception: {0}. User agent: {1}, Request source: {2}{3}{4}{3}{3}",
                                            ex.Message,
                                            selectionParams.RequestSource,
                                            Environment.NewLine,
                                            ex.StackTrace,
                                            DateTime.Now);

                var innerMessages = new List <string>();
                if (exceptions.Count > 0)
                {
                    innerMessages.AddRange(exceptions.Select(exInner => Environment.NewLine + "[MESSAGE] " + exInner.Message + Environment.NewLine + exInner.StackTrace));
                }

                if (innerMessages.Count > 0)
                {
                    message += Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, innerMessages.ToArray());
                    innerMessages.Clear();
                }

                SaveMessageInLogFile(message);
            }
            catch (Exception err)
            {
                System.Diagnostics.Trace.TraceError(err.Message);
            }
        }
示例#8
0
        /// <summary>
        /// Zapisuje do pliku informację o wyjątku
        /// </summary>
        /// <param name="ex">Obiekt wyjątku</param>
        private static void SaveErrorInLogFile(Exception ex)
        {
            try
            {
                if (ex == null)
                {
                    return;
                }

                var message = string.Format("{0}{1}Exception: {2}. {3}{3}",
                                            DateTime.Now,
                                            Environment.NewLine,
                                            ex.Message,
                                            ex.StackTrace);

                var exceptions = new List <Exception>();
                ExceptionsHandlingHelper.HierarchizeError(ex, ref exceptions);

                var innerMessages = new List <string>();
                if (exceptions.Count > 0)
                {
                    innerMessages.AddRange(exceptions.Select(exInner => ex.Message + Environment.NewLine + ex.StackTrace));
                }

                if (innerMessages.Count > 0)
                {
                    message += Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, innerMessages.ToArray());
                    innerMessages.Clear();
                }

                SaveMessageInLogFile(message);
            }
            catch (Exception err)
            {
                System.Diagnostics.Trace.TraceError(err.Message);
            }
        }
示例#9
0
        public ApiResponse Save(Entities.StatisticsEntry statisticsEntry)
        {
            var response = new ApiResponse();

            statisticsEntry.Statistics.Name = "Stats";
            using (var transaction = Context.Database.BeginTransaction())
            {
                try
                {
                    var dbEntry = new Statistic();
                    dbEntry.Name = "Stats";

                    #region zapis danych podstawowych statystyk

                    if (statisticsEntry.Statistics.Id == 0)
                    {
                        dbEntry.Data1 = statisticsEntry.Statistics.Data1 ?? "";
                        dbEntry.MultimediaObjectId = statisticsEntry.Statistics.MultimediaObjectId;
                        dbEntry.Data2         = statisticsEntry.Statistics.Data2 ?? "";
                        dbEntry.Data3         = statisticsEntry.Statistics.Data3 ?? "";
                        dbEntry.Data4         = "";
                        dbEntry.RequestDate   = statisticsEntry.Statistics.RequestDate;
                        dbEntry.RequestIP     = statisticsEntry.Statistics.RequestIP;
                        dbEntry.RequestSource = statisticsEntry.Statistics.RequestSource;
                        statisticsEntry.Statistics.ResponseDate = DateTime.Now;
                        dbEntry.ResponseDate = statisticsEntry.Statistics.ResponseDate;
                        dbEntry.SessionId    = statisticsEntry.Statistics.SessionId;
                        dbEntry.Clicked      = statisticsEntry.Statistics.Clicked;
                        dbEntry.AdPoints     = statisticsEntry.Statistics.AdPoints;
                        dbEntry.DeviceId     = statisticsEntry.Statistics.DeviceId;
                        dbEntry.UserId       = statisticsEntry.Statistics.UserId;
                        dbEntry.CampaignId   = statisticsEntry.Statistics.CampaignId;
                        Context.Statistics.Add(dbEntry);
                        Context.SaveChanges();
                    }

                    #endregion zapis danych podstawowych statystyk

                    #region zapis powiązań statystyki z kampaniami

                    //foreach (var cp in statisticsEntry.SelectedMultimediaObjectCampaigns)
                    //{
                    //	//Context.Statistics_Campaign.Add(new Statistics_Campaign
                    //	//{
                    //	//	CampaignId = cp.CampaignId,
                    //	//	StatisticsId = dbEntry.Id
                    //	//});
                    //	//Context.SaveChanges();
                    //}

                    #endregion zapis powiązań statystyki z kampaniami

                    #region zapis powiązań statystyki z kategoriami

                    foreach (var cp in statisticsEntry.Categories)
                    {
                        //Context.Statistics_Category.Add(new Statistics_Category
                        //{
                        //	CategoryId = cp.Value,
                        //	StatisticsId = dbEntry.Id
                        //});
                        //Context.SaveChanges();
                    }

                    #endregion zapis powiązań statystyki z kategoriami

                    transaction.Commit();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    // Obsługa błędów EF
                    using (var handler = new DbValidationErrorHandler(ex))
                    {
                        if (handler.HasErrors)
                        {
                            response.Errors.AddRange(handler.ValidationErrors);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Obsługa błędów pozostałych
                    var hierarchy = new List <Exception>();
                    ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                    if (hierarchy.Count > 0)
                    {
                        response.Errors.AddRange(
                            hierarchy.Select(s => new ApiValidationErrorItem {
                            Message = s.Message + Environment.NewLine + s.StackTrace
                        })
                            .Distinct()
                            .AsEnumerable());
                    }
                }

                if (response.Errors.Count > 0)
                {
                    transaction.Rollback();
                }

                response.Accepted = response.Errors.Count == 0;
                return(response);
            }
        }
示例#10
0
        /// <summary>
        /// Zapisywanie/Modyfikacja użytkownika
        /// </summary>
        /// <param name="user">Użytkownik</param>
        /// <returns>Odpowiedź funkcji</returns>
        public ApiResponse Save(User user)
        {
            var response = new ApiResponse {
                Errors = new List <ApiValidationErrorItem>()
            };

            #region Errors

            if (user.RoleId == 0)
            {
                response.Errors.Add(new ApiValidationErrorItem {
                    Property = "Role", Message = "Nieprawidłowe uprawnienia użytkownika"
                });
                response.Accepted = false;
                return(response);
            }

            #endregion Errors

            using (var transaction = Context.Database.BeginTransaction())
            {
                try
                {
                    User dbEntry;

                    #region Zapis danych podstawowych kampanii

                    if (user.Id > 0)
                    {
                        dbEntry = Context.Users.FirstOrDefault(f => f.Id == user.Id);
                        if (dbEntry != null)
                        {
                            if (!string.IsNullOrEmpty(user.Name))
                            {
                                dbEntry.Name = user.Name;
                            }
                            if (!string.IsNullOrEmpty(user.LastName))
                            {
                                dbEntry.LastName = user.LastName;
                            }
                            if (!string.IsNullOrEmpty(user.FirstName))
                            {
                                dbEntry.FirstName = user.FirstName;
                            }
                            if (!string.IsNullOrEmpty(user.Password))
                            {
                                dbEntry.Password = user.Password;
                            }
                            if (user.CompanyAddress != null)
                            {
                                dbEntry.CompanyAddress = user.CompanyAddress;
                            }
                            if (user.CompanyName != null)
                            {
                                dbEntry.CompanyName = user.CompanyName;
                            }
                            if (user.AdditionalInfo != null)
                            {
                                dbEntry.AdditionalInfo = user.AdditionalInfo;
                            }
                            if (!string.IsNullOrEmpty(user.Email))
                            {
                                dbEntry.Email = user.Email;
                            }
                            if (!string.IsNullOrEmpty(user.Url))
                            {
                                dbEntry.Url = user.Url;
                            }
                            dbEntry.RoleId    = user.RoleId;
                            dbEntry.AdPoints  = user.AdPoints;
                            dbEntry.IsBlocked = user.IsBlocked;
                            Context.SaveChanges();
                        }
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(user.Name))
                        {
                            response.Errors.Add(new ApiValidationErrorItem {
                                Property = "Name", Message = "Nieprawidłowe dane"
                            });
                            response.Accepted = false;
                            return(response);
                        }
                        dbEntry = new User
                        {
                            Name           = user.Name,
                            LastName       = user.LastName,
                            FirstName      = user.FirstName,
                            Password       = user.Password,
                            Email          = user.Email,
                            AdditionalInfo = user.AdditionalInfo,
                            CompanyName    = user.CompanyName,
                            CompanyAddress = user.CompanyAddress,
                            Url            = user.Url,
                            IsBlocked      = user.IsBlocked,
                            RoleId         = user.RoleId,
                            AdPoints       = user.AdPoints
                        };
                        Context.Users.Add(dbEntry);
                        Context.SaveChanges();

                        var device    = new Device();
                        var devRepo   = new EFDeviceRepository();
                        var imageRepo = new EFMultimediaObjectRepository();
                        var u         = Context.Campaigns.FirstOrDefault(it => it.Name == "LogoEC2" && it.User.Role.Name == "Admin");

                        device.Name        = "LogoEC2";
                        device.Description = "Przykładowa kampania AdServera";
                        device.TypeId      = (int)u.MultimediaObjects.First().TypeId;
                        device.UserId      = dbEntry.Id;

                        var camps = new List <Campaign>();
                        var cats  = new List <Category>();
                        camps.Add(u);
                        cats.AddRange(u.Categories);

                        device.Campaigns.Add(u);
                        //device.Categories = u.Categories;
                        devRepo.Save(device);
                        dbEntry.Devices = new Collection <Device> {
                            device
                        };
                        Context.SaveChanges();
                    }

                    #endregion Zapis danych podstawowych kampanii

                    transaction.Commit();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    // Obsługa błędów EF
                    using (var handler = new DbValidationErrorHandler(ex))
                    {
                        if (handler.HasErrors)
                        {
                            response.Errors.AddRange(handler.ValidationErrors);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Obsługa błędów pozostałych
                    var hierarchy = new List <Exception>();
                    ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                    if (hierarchy.Count > 0)
                    {
                        response.Errors.AddRange(hierarchy.Select(s => new ApiValidationErrorItem {
                            Message = s.Message + Environment.NewLine + s.StackTrace
                        }).Distinct().AsEnumerable());
                    }
                }

                if (response.Errors.Count > 0)
                {
                    transaction.Rollback();
                }
            }

            response.Accepted = response.Errors.Count == 0;
            return(response);
        }
示例#11
0
        /// <summary>
        /// Zapisuje obiekt multimedialny do bazy
        /// </summary>
        /// <param name="multimediaObject">Obiekt multimedialny</param>
        public ApiResponse Save(MultimediaObject multimediaObject, List <Campaign> Camps)
        {
            var response = new ApiResponse();

            if (!string.IsNullOrEmpty(multimediaObject.FileContent))
            {
                var index = multimediaObject.FileContent.IndexOf("base64,");
                if (index != -1)
                {
                    multimediaObject.FileContent = multimediaObject.FileContent.Substring(index + "base64,".Length);
                }
                if (multimediaObject.Url == null)
                {
                    throw new Exception("Nie ustawiono adres URL dla obiektu!");
                }

                using (var transaction = Context.Database.BeginTransaction())
                {
                    try
                    {
                        dynamic dbEntry;
                        var     multimediaObjectType = Context.Types.FirstOrDefault(x => x.Id == multimediaObject.TypeId);
                        if (multimediaObjectType == null)
                        {
                            throw new Exception("Nie znaleziono wskazanego typu obiektu. Możliwe zmiany na innym stanowisku.");
                        }

                        // Konwersja formatu base64 na tablicę bajtów
                        var imageBytes = Convert.FromBase64String(multimediaObject.FileContent);

                        byte[] thumbnail = imageBytes;

                        #region Zapis danych podstawowych obiektu
                        if (multimediaObject.Id > 0)
                        {
                            dbEntry = Context.MultimediaObjects.SingleOrDefault(f => f.Id == multimediaObject.Id);
                            if (dbEntry != null)
                            {
                                dbEntry.UserId = multimediaObject.UserId;

                                dbEntry.FileName  = multimediaObject.FileName;
                                dbEntry.MimeType  = multimediaObject.MimeType;
                                dbEntry.Name      = multimediaObject.Name;
                                dbEntry.TypeId    = multimediaObject.TypeId;
                                dbEntry.Url       = multimediaObject.Url;
                                dbEntry.Contents  = imageBytes;
                                dbEntry.Thumbnail = thumbnail;

                                SetRelation(multimediaObject, ref dbEntry);
                                Context.SaveChanges();
                            }
                        }
                        else
                        {
                            ICollection <Campaign> CampList = new List <Campaign>();
                            foreach (var camp in Camps)
                            {
                                Campaign c = Context.Campaigns.FirstOrDefault(p => p.Id == camp.Id);
                                Context.Campaigns.Attach(c);
                                CampList.Add(c);
                            }

                            dbEntry = new MultimediaObject
                            {
                                FileName  = multimediaObject.FileName,
                                MimeType  = multimediaObject.MimeType,
                                Name      = multimediaObject.Name,
                                TypeId    = multimediaObject.TypeId,
                                Url       = multimediaObject.Url,
                                Contents  = imageBytes,
                                Thumbnail = thumbnail,
                                UserId    = multimediaObject.UserId,
                                Campaigns = CampList,
                                Content   = multimediaObject.Contents,
                            };

                            SetRelation(multimediaObject, ref dbEntry);

                            Context.MultimediaObjects.Add(dbEntry);
                            Context.SaveChanges();
                        }
                        #endregion


                        transaction.Commit();
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                    {
                        // Obsługa błędów EF
                        using (var handler = new DbValidationErrorHandler(ex))
                        {
                            if (handler.HasErrors)
                            {
                                response.Errors.AddRange(handler.ValidationErrors);
                            }
                        }
                    }

                    catch (Exception ex)
                    {
                        // Obsługa błędów pozostałych
                        var hierarchy = new List <Exception>();
                        ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                        if (hierarchy.Count > 0)
                        {
                            response.Errors.AddRange(hierarchy.Select(s => new ApiValidationErrorItem {
                                Message = s.Message + Environment.NewLine + s.StackTrace
                            }).Distinct().AsEnumerable());
                        }
                    }

                    if (response.Errors.Count > 0)
                    {
                        transaction.Rollback();
                    }
                }
            }
            else
            {
                response.Errors.Add(new ApiValidationErrorItem {
                    Message = "Należy dołączyć plik multimedialny."
                });
            }

            response.Accepted = response.Errors.Count == 0;
            return(response);
        }
示例#12
0
        /// <summary>
        /// Zapisuje kategorię do bazy danych
        /// </summary>
        /// <param name="category">Obiekt kategorii do zapisu</param>
        public ApiResponse Save(Category category)
        {
            var response = new ApiResponse();

            using (var transaction = Context.Database.BeginTransaction())
            {
                try
                {
                    dynamic dbEntry;

                    if (category.Id > 0)
                    {
                        dbEntry = Context.Categories.FirstOrDefault(f => f.Id == category.Id);
                        if (dbEntry != null)
                        {
                            dbEntry.Name = category.Name;
                            dbEntry.Code = category.Code;
                            SetRelation(category, ref dbEntry);
                            Context.SaveChanges();
                        }
                    }
                    else
                    {
                        dbEntry = new Category
                        {
                            Name = category.Name,
                            Code = category.Code
                        };
                        SetRelation(category, ref dbEntry);
                        Context.Categories.Add(dbEntry);
                        Context.SaveChanges();
                    }

                    transaction.Commit();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    //  Obsługa błędów EF
                    using (var handler = new DbValidationErrorHandler(ex))
                    {
                        if (handler.HasErrors)
                        {
                            response.Errors.AddRange(handler.ValidationErrors);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //  Obsługa błędów pozostałych
                    var hierarchy = new List <Exception>();
                    ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                    if (hierarchy.Count > 0)
                    {
                        response.Errors.AddRange(hierarchy.Select(s => new ApiValidationErrorItem {
                            Message = s.Message + Environment.NewLine + s.StackTrace
                        }).Distinct().AsEnumerable());
                    }
                }

                if (response.Errors.Count > 0)
                {
                    transaction.Rollback();
                }
            }
            response.Accepted = response.Errors.Count == 0;
            return(response);
        }
示例#13
0
        /// <summary>
        /// Zapisuje kampanię do bazy danych
        /// </summary>
        /// <param name="campaign">Obiekt kampanii do zapisu</param>
        /// <param name="decrement">Czy tylko zmniejszanie</param>
        public ApiResponse SaveCampaign(Campaign campaign, bool decrement = false)
        {
            var response = new ApiResponse();

            if (campaign.StartDate == DateTime.MinValue || campaign.StartDate == DateTime.MaxValue)
            {
                response.Errors = new List <ApiValidationErrorItem>
                {
                    new ApiValidationErrorItem
                    {
                        Property = "StartDate",
                        Message  = "Niepoprawna data"
                    }
                };
                response.Accepted = false;
                return(response);
            }

            if (campaign.EndDate == DateTime.MinValue || campaign.StartDate == DateTime.MaxValue)
            {
                response.Errors = new List <ApiValidationErrorItem>
                {
                    new ApiValidationErrorItem
                    {
                        Property = "EndDate",
                        Message  = "Niepoprawna data"
                    }
                };
                response.Accepted = false;
                return(response);
            }

            if (campaign.StartDate.Date > campaign.EndDate.Date)
            {
                response.Errors = new List <ApiValidationErrorItem>
                {
                    new ApiValidationErrorItem
                    {
                        Property = "StartDate",
                        Message  = "Data rozpoczęcia musi być wcześniejsza od daty zakończenia."
                    }
                };
                response.Accepted = false;
                return(response);
            }
            using (var transaction = Context.Database.BeginTransaction())
            {
                try
                {
                    dynamic dbEntry;

                    if (campaign.Id > 0)
                    {
                        dbEntry = Context.Campaigns.FirstOrDefault(f => f.Id == campaign.Id);

                        if (dbEntry != new Campaign())
                        {
                            if (dbEntry == null)
                            {
                                response.Errors = new List <ApiValidationErrorItem>
                                {
                                    new ApiValidationErrorItem
                                    {
                                        Property = "Id",
                                        Message  = "Brak kampanii"
                                    }
                                };
                                response.Accepted = false;
                                return(response);
                            }
                            dbEntry.UserId      = campaign.UserId;
                            dbEntry.Description = campaign.Description;
                            dbEntry.EndDate     = campaign.EndDate;
                            dbEntry.IsActive    = campaign.IsActive;
                            dbEntry.Name        = campaign.Name;
                            dbEntry.PriorityId  = campaign.PriorityId;
                            dbEntry.StartDate   = campaign.StartDate;
                            dbEntry.ViewValue   = campaign.ViewValue;
                            dbEntry.ClickValue  = campaign.ClickValue;
                            if (!decrement)
                            {
                                SetRelation(campaign, ref dbEntry);
                            }

                            var duser = Context.Users.First(it => it.Id == campaign.UserId);

                            if (!decrement)
                            {
                                if (dbEntry.AdPoints != campaign.AdPoints && ((dbEntry.AdPoints - campaign.AdPoints) > duser.AdPoints || campaign.AdPoints < 0))
                                {
                                    response.Errors = new List <ApiValidationErrorItem>
                                    {
                                        new ApiValidationErrorItem
                                        {
                                            Property = "AdPoints",
                                            Message  = "Nierawidłowa ilość punktów na kamapanie"
                                        }
                                    };
                                    response.Accepted = false;
                                    return(response);
                                }

                                if (dbEntry.AdPoints != campaign.AdPoints && !(dbEntry.AdPoints - campaign.AdPoints > duser.AdPoints || campaign.AdPoints < 0))
                                {
                                    duser.AdPoints += dbEntry.AdPoints - campaign.AdPoints;
                                }
                            }
                            dbEntry.AdPoints = campaign.AdPoints < 0 ? 0 : campaign.AdPoints;

                            Context.SaveChanges();
                        }
                    }
                    else
                    {
                        dbEntry = new Campaign
                        {
                            Description = campaign.Description,
                            EndDate     = campaign.EndDate,
                            IsActive    = campaign.IsActive,
                            Name        = campaign.Name,
                            PriorityId  = campaign.PriorityId,
                            StartDate   = campaign.StartDate,
                            UserId      = campaign.UserId ?? 0,
                            AdPoints    = campaign.AdPoints,
                            ViewValue   = campaign.ViewValue,
                            ClickValue  = campaign.ClickValue
                        };

                        var dbUser = Context.Users.First(it => it.Id == campaign.UserId);
                        if (dbEntry.AdPoints != campaign.AdPoints)
                        {
                            dbUser.AdPoints -= campaign.AdPoints;
                        }

                        if (dbEntry.AdPoints != campaign.AdPoints || (campaign.AdPoints > dbUser.AdPoints || campaign.AdPoints < 0))
                        {
                            response.Errors = new List <ApiValidationErrorItem>
                            {
                                new ApiValidationErrorItem
                                {
                                    Property = "AdPoints",
                                    Message  = "Nierawidłowa ilość punktów na kamapanie"
                                }
                            };
                            response.Accepted = false;
                            return(response);
                        }

                        SetRelation(campaign, ref dbEntry);

                        Context.Campaigns.Add(dbEntry);
                        Context.SaveChanges();
                    }

                    transaction.Commit();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    // Obsługa błędów EF
                    using (var handler = new DbValidationErrorHandler(ex))
                    {
                        if (handler.HasErrors)
                        {
                            response.Errors.AddRange(handler.ValidationErrors);
                        }
                    }
                }

                catch (Exception ex)
                {
                    // Obsługa błędów pozostałych
                    var hierarchy = new List <Exception>();
                    ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                    if (hierarchy.Count > 0)
                    {
                        response.Errors.AddRange(hierarchy.Select(s => new ApiValidationErrorItem {
                            Message = s.Message + Environment.NewLine + s.StackTrace
                        }).Distinct().AsEnumerable());
                    }
                }

                if (response.Errors.Count > 0)
                {
                    transaction.Rollback();
                }
            }

            response.Accepted = response.Errors.Count == 0;
            return(response);
        }
示例#14
0
        public ActionResult Index(string data0, string data1, string data2, string data3, int Id, string viewId)
        {
            var errors     = new List <string>();
            var nameCookie = "AdServer" + viewId;

            try
            {
                var selectionRequest = new MultimediaObjectSelection.MultimediaObjectsSelectionParams
                {
                    ID            = Id,
                    Data0         = data0,
                    Data1         = data1,
                    Data2         = data2,
                    Data3         = data3,
                    RequestDate   = DateTime.Now,
                    RequestSource = (int)Statistic.RequestSourceType.WWW
                };
                var ips = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                selectionRequest.RequestIP = !string.IsNullOrEmpty(ips) ? ips.Split(',')[0] : Request.ServerVariables["REMOTE_ADDR"];

                var sessionId = Request.Cookies.Get(nameCookie) == null?Guid.NewGuid().ToString() : Request.Cookies[nameCookie]["sessionId"];

                selectionRequest.SessionId = sessionId;

                var cookie = new HttpCookie(nameCookie);
                cookie.Values.Add("sessionId", sessionId);

                using (var ctx = new AdServContext())
                {
                    var repositories = EFRepositorySet.CreateRepositorySet(ctx);

                    try
                    {
                        var           mos = new MultimediaObjectSelection(repositories);
                        List <string> err = new List <string>();

                        const string key    = "FILESTREAM_OPTION";
                        var          urlKey = ConfigurationManager.AppSettings[key];

                        bool filestreamOption = false;
                        if (urlKey != null && !string.IsNullOrEmpty(urlKey))
                        {
                            bool.TryParse(urlKey, out filestreamOption);
                        }

                        bool add = true;
                        if (Request.UrlReferrer != null)
                        {
                            if (Request.Url.Host == Request.UrlReferrer.Host)
                            {
                                add = false;
                            }
                        }
                        AdFile response = mos.GetMultimediaObject(selectionRequest, filestreamOption, add, out err);
                        cookie.Values.Add("cmp", response.CmpId.ToString());

                        if (err != null && err.Count > 0)
                        {
                            errors.AddRange(err);
                        }
                        else
                        {
                            cookie.Values.Add("Id", response.ID.ToString());
                            cookie.Values.Add("StatusCode", response.StatusCode.ToString());
                            Response.AppendCookie(cookie);
                            return(File(response.Contents, response.MimeType));
                        }
                    }
                    catch (Exception ex)
                    {
                        var hierarchy = new List <Exception>();
                        ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                        if (hierarchy.Count > 0)
                        {
                            errors.AddRange(hierarchy.Select(s => s.Message + Environment.NewLine + s.StackTrace).Distinct().AsEnumerable());
                        }

                        SaveErrorInLogFile(selectionRequest, ex);
                    }
                }
            }
            catch (Exception ex)
            {
                var hierarchy = new List <Exception>();
                ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                if (hierarchy.Count > 0)
                {
                    errors.AddRange(hierarchy.Select(s => s.Message + Environment.NewLine + s.StackTrace).Distinct().AsEnumerable());
                }

                SaveErrorInLogFile(ex);
            }
            return(null);
        }
示例#15
0
        public int GetMultimediaObjectBytes(string sessionId,
                                            int id,
                                            string Data0,
                                            string Data1,
                                            string Data2,
                                            string Data3,
                                            DateTime date,
                                            int requestType)
        {
            List <string> errors = null;

            try
            {
                var request = new GetMultimediaObject_Request
                {
                    ID            = id,
                    SessionId     = sessionId,
                    Data0         = Data0,
                    Data1         = Data1,
                    Data2         = Data2,
                    Data3         = Data3,
                    RequestDate   = date,
                    RequestSource = requestType
                };
                // pobranie obiektu multimedialnego
                var response = GetMultimediaObject(request, out errors);

                if (response != null)
                {
                    // jeśli podczas pobrania obiektu wystąpiły błędy, zapisujemy je do pliku z logami
                    if (errors != null && errors.Any())
                    {
                        foreach (var error in response.ErrorMessage)
                        {
                            SaveMessageInLogFile(error);
                        }

                        errors.Clear();
                    }

                    // jeśli istnieje plik obiektu multimedialnego, zwracamy go w postaci bajtów
                    if (response.File != null && response.File.Contents != null)
                    {
                        Context.Response.ContentType = response.File.MimeType;
                        Context.Response.BinaryWrite(response.File.Contents);
                        Context.Response.StatusCode = 200;
                        return(1);
                    }
                }
            }
            catch (Exception ex)
            {
                var hierarchy = new List <Exception>();
                ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);

                if (hierarchy.Count > 0)
                {
                    if (errors == null)
                    {
                        errors = new List <string>();
                    }

                    errors.AddRange(hierarchy.Select(s => s.Message + Environment.NewLine + s.StackTrace).Distinct().AsEnumerable());
                }

                SaveErrorInLogFile(ex);
            }

            return(0);
        }
示例#16
0
        private void StaticClicked(GetMultimediaObject_Request request, int id, int statusCode)
        {
            var errors    = new List <string>();
            var hierarchy = new List <Exception>();

            try
            {
                if (request != null)
                {
                    var selectionRequest = new MultimediaObjectSelection.MultimediaObjectsSelectionParams
                    {
                        Data0         = request.Data0,
                        Data1         = request.Data1,
                        Data2         = request.Data2,
                        Data3         = request.Data3,
                        ID            = id,
                        RequestDate   = DateTime.Now,
                        SessionId     = request.SessionId,
                        RequestSource =
                            (int)
                            (System.Web.HttpContext.Current.Request.UserAgent == null
                                                                        ? Statistic.RequestSourceType.Desktop
                                                                        : Statistic.RequestSourceType.WWW),
                        RequestIP = HttpContext.Current.Request.UserHostAddress
                    };

                    using (var ctx = new AdServContext())
                    {
                        var repositories = EFRepositorySet.CreateRepositorySet(ctx);

                        try
                        {
                            var mos = new MultimediaObjectSelection(repositories);

                            const string key    = "FILESTREAM_OPTION";
                            var          urlKey = ConfigurationManager.AppSettings[key];

                            if (urlKey != null && !string.IsNullOrEmpty(urlKey))
                            {
                                bool filestreamOption;
                                bool.TryParse(urlKey, out filestreamOption);
                            }

                            mos.SaveStatisticsEntry(selectionRequest, new AdFile {
                                ID = id, StatusCode = statusCode
                            }, true);
                        }
                        catch (Exception ex)
                        {
                            ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                            if (hierarchy.Count > 0)
                            {
                                errors.AddRange(hierarchy.Select(s => s.Message + Environment.NewLine + s.StackTrace).Distinct().AsEnumerable());
                            }
                            SaveErrorInLogFile(selectionRequest, ex);
                        }
                    }
                }
                else
                {
                    errors.Add("Parametr requesta nie może być nullem.");
                }
            }
            catch (Exception ex)
            {
                ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy);
                if (hierarchy.Count > 0)
                {
                    errors.AddRange(hierarchy.Select(s => s.Message + Environment.NewLine + s.StackTrace).Distinct().AsEnumerable());
                }
                SaveErrorInLogFile(ex);
            }
        }