Exemplo n.º 1
0
        // GET: SegmentArticles/Articlelist/id of segment
        public async Task <IActionResult> UserArticleSearch(string searchString)
        {
            if (searchString == null)
            {
                return(NotFound());
            }
            _user = _context.User.FirstOrDefault(p => p.EmailAddress == _userManager.GetUserAsync(User).GetAwaiter().GetResult().Email);
            _cpy  = _context.Company.FirstOrDefaultAsync(m => m.ID == _user.CompanyID).GetAwaiter().GetResult();
            var segmentid = HttpContext.Session.GetInt32("SegmentListID");

            DataAccessLayer dla = new DataAccessLayer(_context);

            //Also add the Segment to the Viewbag so we can get the Image
            CompanySegment cs = await _context.CompanySegment.FirstOrDefaultAsync(m => m.ID == segmentid && m.CompanyID == _cpy.ID);

            var segmentArticle = dla.GetArticlesListBasedOnThisUsersFilters(_user, "", cs);

            ViewBag.Segment = cs;
            if (segmentArticle == null)
            {
                return(NotFound());
            }
            ViewBag.UploadsLocation = "https://s3-us-west-2.amazonaws.com/wootrixv2uploadfiles/images/Uploads/";
            return(View(segmentArticle));
        }
Exemplo n.º 2
0
        // POST: SegmentArticles/Delete/5

        public async Task <IActionResult> RemoveFromMagazine(int id)
        {
            var segmentArticle = await _context.SegmentArticle.FindAsync(id);

            DataAccessLayer dla = new DataAccessLayer(_context);

            var            segID = HttpContext.Session.GetInt32("SegmentID") ?? 0;
            CompanySegment cs    = await _context.CompanySegment.FindAsync(segID);

            dla.DeleteArticleAndUpdateOthersOrder(segmentArticle, cs.Title);
            return(RedirectToAction("Details", "CompanySegments", new { id = segID }));
        }
Exemplo n.º 3
0
        internal CompanyDetail GetCompanies(int id)
        {
            var parameters = new List <SqlParameter>();

            parameters.Add(new SqlParameter("@companyId", SqlDbType.Int)
            {
                Value = id
            });

            var dataSet        = dbHelper.SelectDataSet("spCompanyDetails_Get", parameters.ToArray());
            var companyDetails = new CompanyDetail();
            var incomeInfo     = new List <CompanyIncome>();

            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
            {
                var info = new CompanyIncome();
                info.Id          = dataRow["id"] == DBNull.Value ? 1 : Convert.ToInt32(dataRow["id"]);
                info.RowHeader   = dataRow["RowHeader"] == DBNull.Value ? "" : Convert.ToString(dataRow["RowHeader"]);
                info.ValueCell1  = dataRow["valueCell1"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell1"]);
                info.ValueCell2  = dataRow["valueCell2"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell2"]);
                info.ValueCell3  = dataRow["valueCell3"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell3"]);
                info.ValueCell4  = dataRow["valueCell4"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell4"]);
                info.ValueCell5  = dataRow["valueCell5"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell5"]);
                info.IsHeaderRow = dataRow["isHeaderRow"] == DBNull.Value ? 1 : Convert.ToInt32(dataRow["isHeaderRow"]);
                info.SheetName   = dataRow["sheetName"] == DBNull.Value ? "" : Convert.ToString(dataRow["sheetName"]);
                info.CompanyId   = dataRow["companyId"] == DBNull.Value ? 0 : Convert.ToInt32(dataRow["companyId"]);
                incomeInfo.Add(info);
            }
            companyDetails.CompanyIncomeInfo = incomeInfo;

            var segmentInfo = new List <CompanySegment>();

            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
            {
                var info = new CompanySegment();
                info.Id          = dataRow["id"] == DBNull.Value ? 1 : Convert.ToInt32(dataRow["id"]);
                info.RowHeader   = dataRow["RowHeader"] == DBNull.Value ? "" : Convert.ToString(dataRow["RowHeader"]);
                info.ValueCell1  = dataRow["valueCell1"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell1"]);
                info.ValueCell2  = dataRow["valueCell2"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell2"]);
                info.ValueCell3  = dataRow["valueCell3"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell3"]);
                info.ValueCell4  = dataRow["valueCell4"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell4"]);
                info.ValueCell5  = dataRow["valueCell5"] == DBNull.Value ? "" : Convert.ToString(dataRow["valueCell5"]);
                info.IsHeaderRow = dataRow["isHeaderRow"] == DBNull.Value ? 1 : Convert.ToInt32(dataRow["isHeaderRow"]);
                info.SheetName   = dataRow["sheetName"] == DBNull.Value ? "" : Convert.ToString(dataRow["sheetName"]);
                info.CompanyId   = dataRow["companyId"] == DBNull.Value ? 0 : Convert.ToInt32(dataRow["companyId"]);
                segmentInfo.Add(info);
            }
            companyDetails.CompanySegments = segmentInfo;


            return(companyDetails);
        }
Exemplo n.º 4
0
        // GET: CompanySegments/Details/5
        public async Task <IActionResult> Details(int id)
        {
            _user = _context.User.FirstOrDefault(p => p.EmailAddress == _userManager.GetUserAsync(User).GetAwaiter().GetResult().Email);
            _cpy  = _context.Company.FirstOrDefaultAsync(m => m.ID == _user.CompanyID).GetAwaiter().GetResult();

            HttpContext.Session.SetInt32("SegmentID", id);
            CompanySegment cs = await _context.CompanySegment.FirstOrDefaultAsync(m => m.ID == id && m.CompanyID == _cpy.ID);

            var segmentArticle = _context.SegmentArticle
                                 .Where(n => n.CompanyID == _cpy.ID)
                                 .Where(m => m.Segments.Contains(cs.Title));

            // OK so now we are going to set the article Order field to be as show in the Segments so its easier to work with.
            // We will need to save the segments back again if there is a change

            foreach (SegmentArticle item in segmentArticle)
            {
                //Split the segments into a list, grab their order and increment it then save the change
                var segments     = item.Segments;
                var segmentsList = item.Segments.Split("|");
                foreach (string segmentTitleAndOrder in segmentsList)
                {
                    if (segmentTitleAndOrder.Contains(cs.Title))
                    {
                        //Get the order and increment
                        var  titleAndOrder = segmentTitleAndOrder.Split("/");
                        bool success       = int.TryParse(titleAndOrder[1], out int ord);

                        // Set the article Order
                        item.Order = ord;
                    }
                }
                _context.Update(item);
            }

            _context.SaveChanges();
            segmentArticle = _context.SegmentArticle
                             .Where(n => n.CompanyID == cs.CompanyID)
                             .Where(m => m.Segments.Contains(cs.Title))
                             .OrderBy(p => p.Order);

            //Also add the Segment to the Viewbag so we can get the Image
            ViewBag.Segment = cs;

            if (segmentArticle == null)
            {
                return(NotFound());
            }

            return(View(await segmentArticle.ToListAsync()));
        }
Exemplo n.º 5
0
        public void SaveCompanySegment(CompanySegment companySegment)
        {
            var parameters = new List <SqlParameter>();

            parameters.Add(new SqlParameter("@rowHeader", SqlDbType.NVarChar)
            {
                Value = companySegment.RowHeader
            });
            parameters.Add(new SqlParameter("@valueCell1", SqlDbType.NVarChar)
            {
                Value = companySegment.ValueCell1 ?? ""
            });
            parameters.Add(new SqlParameter("@valueCell2", SqlDbType.NVarChar)
            {
                Value = companySegment.ValueCell2 ?? ""
            });
            parameters.Add(new SqlParameter("@valueCell3", SqlDbType.NVarChar)
            {
                Value = companySegment.ValueCell3 ?? ""
            });
            parameters.Add(new SqlParameter("@valueCell4", SqlDbType.NVarChar)
            {
                Value = companySegment.ValueCell4 ?? ""
            });
            parameters.Add(new SqlParameter("@valueCell5", SqlDbType.NVarChar)
            {
                Value = companySegment.ValueCell5 ?? ""
            });
            parameters.Add(new SqlParameter("@isHeaderRow", SqlDbType.Int)
            {
                Value = companySegment.IsHeaderRow
            });
            parameters.Add(new SqlParameter("@sheetName", SqlDbType.NVarChar)
            {
                Value = companySegment.SheetName
            });
            parameters.Add(new SqlParameter("@companyId", SqlDbType.Int)
            {
                Value = companySegment.CompanyId
            });

            dbHelper.ExecuteNonQuery("spCompanySegment_Save", parameters.ToArray());
        }
Exemplo n.º 6
0
        // GET: SegmentArticles/Articlelist/id of segment
        public async Task <IActionResult> ArticleList(int id)
        {
            _user = _context.User.FirstOrDefault(p => p.EmailAddress == _userManager.GetUserAsync(User).GetAwaiter().GetResult().Email);
            _cpy  = _context.Company.FirstOrDefaultAsync(m => m.ID == _user.CompanyID).GetAwaiter().GetResult();
            HttpContext.Session.SetInt32("SegmentListID", id);


            HttpContext.Session.SetInt32("CompanyID", _cpy.ID);
            HttpContext.Session.SetString("CompanyName", _cpy.CompanyName);
            HttpContext.Session.SetString("CompanyTextMain", _cpy.CompanyTextMain);
            HttpContext.Session.SetString("CompanyTextSecondary", _cpy.CompanyTextSecondary);
            HttpContext.Session.SetString("CompanyMainFontColor", _cpy.CompanyMainFontColor);
            HttpContext.Session.SetString("CompanyLogoImage", _cpy.CompanyLogoImage);
            HttpContext.Session.SetString("CompanyFocusImage", _cpy.CompanyFocusImage ?? "");
            HttpContext.Session.SetString("CompanyBackgroundImage", _cpy.CompanyBackgroundImage ?? "");
            HttpContext.Session.SetString("CompanyHighlightColor", _cpy.CompanyHighlightColor);
            HttpContext.Session.SetString("CompanyHeaderFontColor", _cpy.CompanyHeaderFontColor);
            HttpContext.Session.SetString("CompanyHeaderBackgroundColor", _cpy.CompanyHeaderBackgroundColor);
            HttpContext.Session.SetString("CompanyBackgroundColor", _cpy.CompanyBackgroundColor);
            HttpContext.Session.SetInt32("CompanyNumberOfUsers", _cpy.CompanyNumberOfUsers);
            ViewBag.UploadsLocation = "https://s3-us-west-2.amazonaws.com/wootrixv2uploadfiles/images/Uploads/";

            DataAccessLayer dla = new DataAccessLayer(_context);
            // Now for users we need to show them articles on the home page so get them in the ViewBag for display
            //Also add the Segment to the Viewbag so we can get the Image
            CompanySegment cs = await _context.CompanySegment.FirstOrDefaultAsync(m => m.ID == id && m.CompanyID == _cpy.ID);

            var segmentArticle = dla.GetArticlesListBasedOnThisUsersFilters(_user, "", cs).OrderBy(m => m.Order);

            if (segmentArticle == null)
            {
                return(NotFound());
            }

            ViewBag.SegmentCoverImage = cs.CoverImage ?? "";
            ViewBag.SegmentTitle      = cs.Title ?? "";
            ViewBag.CompanyName       = _user.CompanyName ?? "";

            return(View(segmentArticle));
        }
Exemplo n.º 7
0
        /// <summary>
        /// So pass 4 of the filtering rules:
        /// If user has no filters show all articles
        /// If user has filter x, any article shown must contain x in that group but it will show if it has other filters in that group also
        /// If user has filters x1 and x2, any article shown will have either x1 or x2
        /// If user has filters x and y set from different groups, any article shown must contain those filters in their respective groups
        /// </summary>
        /// <param name="usr"></param>
        /// <param name="articleSearchString"></param>
        /// <param name="seg"></param>
        /// <returns></returns>
        public List <WootrixV2.Models.SegmentArticle> GetArticlesListBasedOnThisUsersFilters(User usr, string articleSearchString, CompanySegment seg)
        {
            List <SegmentArticle> articles = new List <SegmentArticle>();

            try
            {
                var possibleArticles = _context.SegmentArticle.Where(n => n.CompanyID == usr.CompanyID && n.PublishFrom < DateTime.Now && n.Segments.Contains(seg.Title)).AsNoTracking();

                foreach (SegmentArticle art in possibleArticles)
                {
                    if (seg != null && !string.IsNullOrEmpty(seg.Title))
                    {
                        //If no filters for user all articles will show that have no filters.
                        if (ArticleMatchesUserFilters(art, usr))
                        {
                            articles.Add(art);
                        }
                    }
                }

                //Allow for searches too
                if (!string.IsNullOrEmpty(articleSearchString))
                {
                    articles = articles.Where(m => (m.Title.Contains(articleSearchString) || m.Tags.Contains(articleSearchString))).ToList();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Retrieving articles for this user failed with inner exception: " + e);
            }

            // We need better ordering.
            if (articles != null)
            {
                articles.OrderBy(m => m.Order);
            }


            return(articles.ToList());
        }
Exemplo n.º 8
0
        public List <CompanySegment> GetSegmentsList(
            int companyID,
            User usr,
            string segmentSearchString,
            string articleSearchString)
        {
            // ISSUE: object of a compiler-generated type is created
            // ISSUE: variable of a compiler-generated type
            DataAccessLayer.\u003C\u003Ec__DisplayClass17_0 cDisplayClass170 = new DataAccessLayer.\u003C\u003Ec__DisplayClass17_0();
            // ISSUE: reference to a compiler-generated field
            cDisplayClass170.companyID = companyID;
            // ISSUE: reference to a compiler-generated field
            cDisplayClass170.articleSearchString = articleSearchString;
            // ISSUE: reference to a compiler-generated field
            cDisplayClass170.segmentSearchString = segmentSearchString;
            List <CompanySegment> source             = new List <CompanySegment>();
            List <SegmentArticle> segmentArticleList = new List <SegmentArticle>();
            List <SegmentArticle> list = this._context.SegmentArticle.ToList <SegmentArticle>();

            // ISSUE: reference to a compiler-generated field
            if (!string.IsNullOrEmpty(cDisplayClass170.articleSearchString))
            {
                // ISSUE: reference to a compiler-generated field
                // ISSUE: reference to a compiler-generated field
                // ISSUE: reference to a compiler-generated field
                list = this._context.SegmentArticle.Where <SegmentArticle>((Expression <Func <SegmentArticle, bool> >)(n => n.CompanyID == cDisplayClass170.companyID)).Where <SegmentArticle>((Expression <Func <SegmentArticle, bool> >)(m => m.Title.Contains(cDisplayClass170.articleSearchString) || m.Tags.Contains(cDisplayClass170.articleSearchString))).ToList <SegmentArticle>();
            }
            foreach (SegmentArticle segmentArticle in (IEnumerable <SegmentArticle>) this._context.SegmentArticle)
            {
                if (segmentArticle.CompanyID == usr.CompanyID)
                {
                    DateTime?publishFrom = segmentArticle.PublishFrom;
                    DateTime now         = DateTime.Now;
                    if (publishFrom.HasValue && publishFrom.GetValueOrDefault() < now && (segmentArticle.Country == usr.Country && segmentArticle.State == usr.State && segmentArticle.City == usr.City) && (this.PassesFilter(segmentArticle.Groups, usr.Groups) && this.PassesFilter(segmentArticle.TypeOfUser, usr.TypeOfUser) && this.PassesFilter(segmentArticle.Topics, usr.Topics) && this.PassesFilter(segmentArticle.Languages, usr.WebsiteLanguage)))
                    {
                        segmentArticleList.Add(segmentArticle);
                    }
                }
            }
            foreach (SegmentArticle segmentArticle in segmentArticleList)
            {
                foreach (string str in ((IEnumerable <string>)segmentArticle.Segments.Split('|', StringSplitOptions.None)).ToList <string>())
                {
                    // ISSUE: object of a compiler-generated type is created
                    // ISSUE: variable of a compiler-generated type
                    DataAccessLayer.\u003C\u003Ec__DisplayClass17_1 cDisplayClass171 = new DataAccessLayer.\u003C\u003Ec__DisplayClass17_1();
                    // ISSUE: reference to a compiler-generated field
                    cDisplayClass171.CS\u0024\u003C\u003E8__locals1 = cDisplayClass170;
                    // ISSUE: reference to a compiler-generated field
                    cDisplayClass171.justSegTitle = str.Split('/', StringSplitOptions.None);
                    // ISSUE: reference to a compiler-generated method
                    if (source.FirstOrDefault <CompanySegment>(new Func <CompanySegment, bool>(cDisplayClass171.\u003CGetSegmentsList\u003Eb__3)) == null)
                    {
                        // ISSUE: reference to a compiler-generated field
                        // ISSUE: reference to a compiler-generated field
                        if (string.IsNullOrEmpty(cDisplayClass171.CS\u0024\u003C\u003E8__locals1.segmentSearchString))
                        {
                            ParameterExpression parameterExpression;
                            // ISSUE: reference to a compiler-generated field
                            // ISSUE: method reference
                            CompanySegment companySegment = this._context.CompanySegment.FirstOrDefault <CompanySegment>(Expression.Lambda <Func <CompanySegment, bool> >((Expression)Expression.Equal(p.Title, (Expression)Expression.Call(cDisplayClass171.justSegTitle[0], (MethodInfo)MethodBase.GetMethodFromHandle(__methodref(object.ToString)), Array.Empty <Expression>())), parameterExpression));
                            if (companySegment != null)
                            {
                                source.Add(companySegment);
                            }
                        }
                        else
                        {
                            ParameterExpression parameterExpression;
                            // ISSUE: reference to a compiler-generated field
                            // ISSUE: method reference
                            // ISSUE: method reference
                            // ISSUE: method reference
                            // ISSUE: field reference
                            // ISSUE: field reference
                            // ISSUE: method reference
                            // ISSUE: method reference
                            // ISSUE: field reference
                            // ISSUE: field reference
                            CompanySegment companySegment = this._context.CompanySegment.FirstOrDefault <CompanySegment>(Expression.Lambda <Func <CompanySegment, bool> >((Expression)Expression.AndAlso((Expression)Expression.Equal(p.Title, (Expression)Expression.Call(cDisplayClass171.justSegTitle[0], (MethodInfo)MethodBase.GetMethodFromHandle(__methodref(object.ToString)), Array.Empty <Expression>())), (Expression)Expression.OrElse((Expression)Expression.Call((Expression)Expression.Property((Expression)parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(__methodref(CompanySegment.get_Title))), (MethodInfo)MethodBase.GetMethodFromHandle(__methodref(string.Contains)), new Expression[1]
                            {
                                (Expression)Expression.Field((Expression)Expression.Field((Expression)Expression.Constant((object)cDisplayClass171, typeof(DataAccessLayer.\u003C\u003Ec__DisplayClass17_1)), FieldInfo.GetFieldFromHandle(__fieldref(DataAccessLayer.\u003C\u003Ec__DisplayClass17_1.CS\u0024\u003C\u003E8__locals1))), FieldInfo.GetFieldFromHandle(__fieldref(DataAccessLayer.\u003C\u003Ec__DisplayClass17_0.segmentSearchString)))
                            }), (Expression)Expression.Call((Expression)Expression.Property((Expression)parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(__methodref(CompanySegment.get_Tags))), (MethodInfo)MethodBase.GetMethodFromHandle(__methodref(string.Contains)), new Expression[1]
                            {
                                (Expression)Expression.Field((Expression)Expression.Field((Expression)Expression.Constant((object)cDisplayClass171, typeof(DataAccessLayer.\u003C\u003Ec__DisplayClass17_1)), FieldInfo.GetFieldFromHandle(__fieldref(DataAccessLayer.\u003C\u003Ec__DisplayClass17_1.CS\u0024\u003C\u003E8__locals1))), FieldInfo.GetFieldFromHandle(__fieldref(DataAccessLayer.\u003C\u003Ec__DisplayClass17_0.segmentSearchString)))
                            }))), parameterExpression));
                            if (companySegment != null)
                            {
                                source.Add(companySegment);
                            }
                        }
                    }
                }
            }
            return(source.OrderBy <CompanySegment, int?>((Func <CompanySegment, int?>)(o => o.Order)).ToList <CompanySegment>());
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Edit(int id, CompanySegmentViewModel cps)
        {
            if (id != cps.ID)
            {
                return(NotFound());
            }
            _user = _context.User.FirstOrDefault(p => p.EmailAddress == _userManager.GetUserAsync(User).GetAwaiter().GetResult().Email);
            _cpy  = _context.Company.FirstOrDefaultAsync(m => m.ID == _user.CompanyID).GetAwaiter().GetResult();

            //Initialise a new companysegment
            CompanySegment mySegment = await _context.CompanySegment.FindAsync(id);

            //Have to check the Segment title isn't already used - it gets weird otherwise
            var existingSeg = _context.SegmentArticle.FirstOrDefault(n => n.Title == cps.Title && n.CompanyID == cps.CompanyID);

            if (existingSeg == null)
            {
                if (ModelState.IsValid)
                {
                    //ID,Order,Title,CoverImage,CoverImageMobileFriendly,PublishDate,FinishDate,ClientName,ClientLogoImage,ThemeColor,StandardColor,Draft,Department,Tags
                    mySegment.CompanyID = _user.CompanyID;


                    mySegment.PublishDate   = cps.PublishDate;
                    mySegment.FinishDate    = cps.FinishDate;
                    mySegment.ClientName    = cps.ClientName;
                    mySegment.ThemeColor    = cps.ThemeColor;
                    mySegment.StandardColor = cps.StandardColor;
                    mySegment.Draft         = DateTime.Now > cps.PublishDate ? false : true;
                    mySegment.Department    = cps.Department;
                    mySegment.Tags          = cps.Tags;

                    IFormFile coverImage = cps.CoverImage;
                    if (coverImage != null)
                    {
                        await _dla.UploadFileToS3(coverImage, _user.CompanyName + "_" + coverImage.FileName, "images/Uploads");

                        mySegment.CoverImage = coverImage.FileName;
                    }

                    IFormFile coverImageMB = cps.CoverImageMobileFriendly;
                    if (coverImageMB != null)
                    {
                        await _dla.UploadFileToS3(coverImageMB, _user.CompanyName + "_" + coverImageMB.FileName, "images/Uploads");

                        //The file has been saved to disk - now save the file name to the DB
                        mySegment.CoverImageMobileFriendly = coverImageMB.FileName;
                    }

                    IFormFile cli = cps.ClientLogoImage;
                    if (cli != null)
                    {
                        await _dla.UploadFileToS3(cli, _user.CompanyName + "_" + cli.FileName, "images/Uploads");

                        //The file has been saved to disk - now save the file name to the DB
                        mySegment.CoverImageMobileFriendly = cli.FileName;
                    }


                    try
                    {
                        // Done later to avoid ordering failures if the image upload fails.
                        if (mySegment.Order != 1)
                        {
                            // We only need to decrement articles above it (lower order)
                            InsertAtOrder1(mySegment.Order ?? 1);
                        }
                        mySegment.Order = 1;

                        // Ok but what about the connected articles? We need to update every article segments field and change the old val to the new

                        // If the title changed
                        if (mySegment.Title != cps.Title)
                        {
                            foreach (var art in _context.SegmentArticle.Where(m => m.CompanyID == _user.CompanyID))
                            {
                                if (art.Segments.Contains(mySegment.Title))
                                {
                                    var oldSegments = art.Segments;
                                    var newSegments = oldSegments.Replace(mySegment.Title, cps.Title);
                                    art.Segments = newSegments;
                                    _context.Update(art);
                                }
                            }
                        }

                        mySegment.Title = cps.Title;

                        _context.Update(mySegment);
                        await _context.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!CompanySegmentExists(cps.ID))
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }
                    return(RedirectToAction(nameof(Index)));
                }
            }
            else
            {
                // Article title already exists
                ModelState.AddModelError(string.Empty, "Magazine Title already exists - please choose something unique");
            }

            return(RedirectToAction("Edit", new { id = cps.ID }));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Create(CompanySegmentViewModel cps)
        {
            _user = _context.User.FirstOrDefault(p => p.EmailAddress == _userManager.GetUserAsync(User).GetAwaiter().GetResult().Email);
            _cpy  = _context.Company.FirstOrDefaultAsync(m => m.ID == _user.CompanyID).GetAwaiter().GetResult();

            var companyID = _cpy.ID;
            //Initialise a new companysegment
            var mySegment = new CompanySegment();

            if (ModelState.IsValid)
            {
                //ID,Order,Title,CoverImage,CoverImageMobileFriendly,PublishDate,FinishDate,ClientName,ClientLogoImage,ThemeColor,StandardColor,Draft,Department,Tags
                mySegment.CompanyID     = companyID;
                mySegment.Order         = cps.Order ?? 1;
                mySegment.Title         = cps.Title;
                mySegment.PublishDate   = cps.PublishDate;
                mySegment.FinishDate    = cps.FinishDate;
                mySegment.ClientName    = cps.ClientName;
                mySegment.ThemeColor    = cps.ThemeColor;
                mySegment.StandardColor = cps.StandardColor;
                mySegment.Draft         = DateTime.Now > cps.PublishDate ? false : true;
                mySegment.Department    = cps.Department;
                mySegment.Tags          = cps.Tags;
                mySegment.ClientName    = cps.ClientName ?? _user.Name;

                IFormFile coverImage = cps.CoverImage;
                if (coverImage != null)
                {
                    await _dla.UploadFileToS3(coverImage, _user.CompanyName + "_" + coverImage.FileName, "images/Uploads");

                    mySegment.CoverImage = coverImage.FileName;
                }

                IFormFile coverImageMB = cps.CoverImageMobileFriendly;
                if (coverImageMB != null)
                {
                    await _dla.UploadFileToS3(coverImageMB, _user.CompanyName + "_" + coverImageMB.FileName, "images/Uploads");

                    //var filePath = Path.Combine(_rootpath, "images/Uploads", _user.companyName + "_" + coverImageMB.FileName);
                    //using (var stream = new FileStream(filePath, FileMode.Create))
                    //{
                    //    await coverImageMB.CopyToAsync(stream);
                    //}
                    //The file has been saved to disk - now save the file name to the DB
                    mySegment.CoverImageMobileFriendly = coverImageMB.FileName;
                }

                IFormFile cli = cps.ClientLogoImage;
                if (cli != null)
                {
                    await _dla.UploadFileToS3(cli, _user.CompanyName + "_" + cli.FileName, "images/Uploads");

                    //The file has been saved to disk - now save the file name to the DB
                    mySegment.CoverImageMobileFriendly = cli.FileName;
                }
                InsertAtOrder1();
                _context.Add(mySegment);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            DataAccessLayer dla = new DataAccessLayer(_context);

            cps.Departments = dla.GetDepartments(companyID);
            return(View(cps));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> ChangeArticleOrder(string id)
        {
            string[] orderArray = id.Split("|");
            bool     success    = int.TryParse(orderArray[1].ToString(), out int articleID);
            var      _companyID = HttpContext.Session.GetInt32("CompanyID") ?? 0;
            var      article    = await _context.SegmentArticle.FindAsync(articleID);

            int whereItCurrentlyIs = article.Order ?? 0;

            success = int.TryParse(orderArray[0].ToString(), out int whereItIsMovingTo);

            var            segID = HttpContext.Session.GetInt32("SegmentID") ?? 0;
            CompanySegment cs    = await _context.CompanySegment.FirstOrDefaultAsync(m => m.ID == segID && m.CompanyID == _companyID);

            var segmentArticle = _context.SegmentArticle
                                 .Where(n => n.CompanyID == cs.CompanyID)
                                 .Where(m => m.Segments.Contains(cs.Title));

            // So for each segment with an order greater than the order we need to increment the order number
            if (whereItCurrentlyIs < whereItIsMovingTo)
            {
                foreach (var art in segmentArticle.Where(m => m.CompanyID == _companyID && ((m.Order ?? 0) <= whereItIsMovingTo) && (m.Order ?? 0) > whereItCurrentlyIs))
                {
                    var updatedSegmentsAndOrders = "";
                    //Split the segments into a list, grab their order and increment it then save the change
                    var segments     = art.Segments;
                    var segmentsList = art.Segments.Split("|");
                    foreach (string segmentTitleAndOrder in segmentsList)
                    {
                        var ender = "";
                        // If this isn't the last title, add a delimited
                        if (segmentsList.Last() != segmentTitleAndOrder)
                        {
                            ender = "|";
                        }

                        if (segmentTitleAndOrder.Contains(cs.Title))
                        {
                            //Get the order and increment
                            var  titleAndOrder = segmentTitleAndOrder.Split("/");
                            int  ord;
                            bool success2 = int.TryParse(titleAndOrder[1], out ord);
                            ord--;
                            updatedSegmentsAndOrders += titleAndOrder[0] + "/" + ord + ender;
                        }
                        else
                        {
                            // just add it unchanged
                            updatedSegmentsAndOrders += segmentTitleAndOrder + ender;
                        }
                    }
                    art.Segments = updatedSegmentsAndOrders;
                    art.Order--;
                    _context.Update(art);
                }
            }
            else
            {
                foreach (var art in segmentArticle.Where(m => m.CompanyID == _companyID && ((m.Order ?? 0) >= whereItIsMovingTo) && (m.Order ?? 0) < whereItCurrentlyIs))
                {
                    var updatedSegmentsAndOrders = "";
                    //Split the segments into a list, grab their order and increment it then save the change
                    var segments     = art.Segments;
                    var segmentsList = art.Segments.Split("|");
                    foreach (string segmentTitleAndOrder in segmentsList)
                    {
                        var ender = "";
                        // If this isn't the last title, add a delimited
                        if (segmentsList.Last() != segmentTitleAndOrder)
                        {
                            ender = "|";
                        }

                        if (segmentTitleAndOrder.Contains(cs.Title))
                        {
                            //Get the order and increment
                            var  titleAndOrder = segmentTitleAndOrder.Split("/");
                            int  ord;
                            bool success2 = int.TryParse(titleAndOrder[1], out ord);
                            ord++;
                            updatedSegmentsAndOrders += titleAndOrder[0] + "/" + ord + ender;
                        }
                        else
                        {
                            // just add it unchanged
                            updatedSegmentsAndOrders += segmentTitleAndOrder + ender;
                        }
                    }
                    art.Segments = updatedSegmentsAndOrders;
                    art.Order++;
                    _context.Update(art);
                }
            }
            // Update the order of the original Article as well
            article.Order = whereItIsMovingTo;

            var uso     = "";
            var segList = article.Segments.Split("|");

            foreach (string sto in segList)
            {
                var ender = "";
                // If this isn't the last title, add a delimited
                if (segList.Last() != sto)
                {
                    ender = "|";
                }
                if (sto.Contains(cs.Title))
                {
                    //Get the order and increment
                    var to = sto.Split("/");
                    uso += to[0] + "/" + whereItIsMovingTo + ender;
                }
                else
                {
                    // just add it unchanged
                    uso += sto + ender;
                }
            }
            article.Segments = uso;


            _context.Update(article);
            _context.SaveChanges();

            return(RedirectToAction("Details", "CompanySegments", new { id = segID }));
        }