Esempio n. 1
0
 public ActionResult Zalozky()
 {
     using (HlidacStatu.Lib.Data.DbEntities db = new HlidacStatu.Lib.Data.DbEntities())
     {
         var bookmarks = db.Bookmark
                         .AsNoTracking()
                         .Where(m => m.UserId == User.Identity.Name)
                         .OrderByDescending(m => m.Created)
                         .ToArray();
         return(View(bookmarks));
     }
 }
Esempio n. 2
0
        public ActionResult SubjektHlidac(string Id, FormCollection form)
        {
            bool   existing = false;
            string wd_id    = form["wd_id"];
            int    wdId;
            string subject = form["subjekt"];

            using (HlidacStatu.Lib.Data.DbEntities db = new HlidacStatu.Lib.Data.DbEntities())
            {
                string id = this.User.Identity.GetUserId();
                HlidacStatu.Lib.Data.WatchDog wd = null;
                if (!string.IsNullOrEmpty(wd_id) && int.TryParse(wd_id, out wdId))
                {
                    wd       = WatchDog.Load(wdId);
                    existing = wd != null;
                }
                string query = "";
                if (string.IsNullOrEmpty(form["ico"]) && wd != null)
                {
                    wd.Delete();
                    return(RedirectToAction("Watchdogs", "Manage"));
                }
                else if (string.IsNullOrEmpty(form["ico"]))
                {
                    return(Redirect("/Subjekt/" + id));
                }

                query = form["ico"].Split(',').Select(m => "ico:" + m).Aggregate((f, s) => f + " OR " + s);

                if (wd == null)
                {
                    wd = new HlidacStatu.Lib.Data.WatchDog();
                }

                wd.Created        = DateTime.Now;
                wd.UserId         = id;
                wd.StatusId       = 1;
                wd.SearchTerm     = query;
                wd.SearchRawQuery = "icoVazby:" + form["ico"];
                wd.PeriodId       = Convert.ToInt32(form["period"]);
                wd.FocusId        = Convert.ToInt32(form["focus"]);
                wd.Name           = Devmasters.TextUtil.ShortenText(form["wdname"], 50);
                wd.Save();
                return(RedirectToAction("Watchdogs", "Manage"));
            }
        }
Esempio n. 3
0
        private static OsobaEvent CreateEvent(OsobaEvent osobaEvent, string user, DbEntities db)
        {
            if (osobaEvent.OsobaId == 0 && string.IsNullOrWhiteSpace(osobaEvent.Ico))
            {
                throw new Exception("Cant attach event to a person or to a company since their reference is empty");
            }

            osobaEvent.Organizace = ParseTools.NormalizaceStranaShortName(osobaEvent.Organizace);
            osobaEvent.Created    = DateTime.Now;
            db.OsobaEvent.Add(osobaEvent);
            db.SaveChanges();
            if (osobaEvent.OsobaId > 0)
            {
                Osoby.GetById.Get(osobaEvent.OsobaId).FlushCache();
            }
            Audit.Add(Audit.Operations.Update, user, osobaEvent, null);
            return(osobaEvent);
        }
 public static HlidacStatu.Lib.OCR.Api.Result AddNewTask(ItemToOcrType itemType, string itemId, string itemSubType = null, HlidacStatu.Lib.OCR.Api.Client.TaskPriority priority = OCR.Api.Client.TaskPriority.Standard)
 {
     using (DbEntities db = new DbEntities())
     {
         ItemToOcrQueue i = new ItemToOcrQueue();
         i.created     = DateTime.Now;
         i.itemId      = itemId;
         i.itemType    = itemType.ToString();
         i.itemSubType = itemSubType;
         i.priority    = (int)OCR.Api.Client.TaskPriority.Standard;
         db.ItemToOcrQueue.Add(i);
         db.SaveChanges();
         return(new OCR.Api.Result()
         {
             IsValid = OCR.Api.Result.ResultStatus.InQueueWithCallback,
             Id = "uknown"
         });
     }
 }
Esempio n. 5
0
 public static Audit Add <T>(Operations operation, string user, string ipAddress, T newObj, T prevObj)
     where T : IAuditable
 {
     using (DbEntities db = new DbEntities())
     {
         var a = new Audit();
         a.date        = DateTime.Now;
         a.objectId    = newObj?.ToAuditObjectId();
         a.objectType  = newObj?.ToAuditObjectTypeName();
         a.operation   = operation.ToString();
         a.IP          = ipAddress;
         a.userId      = user ?? "";
         a.valueBefore = prevObj?.ToAuditJson() ?? null;
         a.valueAfter  = newObj?.ToAuditJson() ?? null;
         db.Audit.Add(a);
         db.SaveChanges();
         return(a);
     }
 }
        public ActionResult NasiPolitici_GetList()
        {
            if (!Framework.ApiAuth.IsApiAuth(this)
                .Authentificated)
            {
                Response.StatusCode = 401;
                return(Json(ApiResponseStatus.ApiUnauthorizedAccess, JsonRequestBehavior.AllowGet));
            }
            else
            {
                using (var db = new HlidacStatu.Lib.Data.DbEntities())
                {
                    string sql = @"
                        select distinct os.NameId, os.Jmeno, os.Prijmeni
                             , os.JmenoAscii, os.PrijmeniAscii, year(os.Narozeni) RokNarozeni, year(os.Umrti) RokUmrti
	                         , FIRST_VALUE(oes.organizace) OVER(partition by oes.osobaid order by oes.datumod desc) Aktpolstr
	                         , oec.pocet
                          from Osoba os
                          left join OsobaEvent oes on os.InternalId = oes.OsobaId and oes.AddInfo in (N'člen strany',N'předseda strany',N'místopředseda strany') and oes.Type = 7
                          left join (select COUNT(pk) pocet, OsobaId from OsobaEvent group by osobaid) oec on oec.OsobaId = os.InternalId
                         where os.Status = 3";

                    var result = db.Database.SqlQuery <FindPersonDTO>(sql)
                                 .Select(r => new
                    {
                        id           = r.NameId,
                        name         = r.Jmeno,
                        surname      = r.Prijmeni,
                        asciiName    = r.JmenoAscii,
                        asciiSurname = r.PrijmeniAscii,
                        birthYear    = r.RokNarozeni,
                        deathYear    = r.RokUmrti,
                        currentParty = r.Aktpolstr,
                        eventCount   = r.Pocet
                    });

                    string osoby = JsonConvert.SerializeObject(result);

                    return(Content(osoby, "application/json"));
                }
            }
        }
Esempio n. 7
0
 public static Audit Add(Operations operation, string user, string ipAddress,
                         string objectId, string objectType,
                         string newObjSer, string prevObjSer)
 {
     using (DbEntities db = new DbEntities())
     {
         var a = new Audit();
         a.date        = DateTime.Now;
         a.objectId    = objectId;
         a.objectType  = objectType;
         a.operation   = operation.ToString();
         a.IP          = ipAddress;
         a.userId      = user ?? "";
         a.valueBefore = prevObjSer;
         a.valueAfter  = newObjSer ?? "";
         db.Audit.Add(a);
         db.SaveChanges();
         return(a);
     }
 }
        public bool IsInRole(string role)
        {
            using (DbEntities db = new DbEntities())
            {
                //var roleId = db.AspNetRoles.Where(m => m.Name == role).FirstOrDefault();
                string roleId = null;
                using (Devmasters.Core.PersistLib p = new Devmasters.Core.PersistLib())
                {
                    var res = p.ExecuteScalar(Devmasters.Core.Util.Config.GetConfigValue("CnnString"),
                                              System.Data.CommandType.Text, "select id from aspnetroles  where name = @role",
                                              new System.Data.IDataParameter[] { new System.Data.SqlClient.SqlParameter("role", role) });
                    if (Devmasters.Core.PersistLib.IsNull(res))
                    {
                        return(false);
                    }
                }

                return(db.AspNetUserRoles.Any(m => m.UserId == this.Id && m.RoleId == roleId));
            }
        }
Esempio n. 9
0
        private static IQueryable <ItemToOcrQueue> CreateQuery(DbEntities db, ItemToOcrType?itemType, string itemSubType)
        {
            IQueryable <ItemToOcrQueue> sql = null;

            sql = db.ItemToOcrQueue
                  .Where(m => m.done.Equals(null) &&
                         m.started.Equals(null));

            if (itemType != null)
            {
                sql = sql.Where(m => m.itemType == itemType.ToString());
            }

            if (!string.IsNullOrEmpty(itemSubType))
            {
                sql = sql.Where(m => m.itemSubType == itemSubType);
            }

            return(sql);
        }
Esempio n. 10
0
        private static List <Autocomplete> LoadPeople()
        {
            List <Autocomplete> results = new List <Autocomplete>();

            using (DbEntities db = new DbEntities())
            {
                Devmasters.Batch.Manager.DoActionForAll <Osoba>(db.Osoba
                                                                .Where(o => o.Status == (int)Osoba.StatusOsobyEnum.Politik ||
                                                                       o.Status == (int)Osoba.StatusOsobyEnum.Sponzor),

                                                                o =>
                {
                    var synonyms = new Autocomplete[2];
                    synonyms[0]  = new Autocomplete()
                    {
                        Id           = $"osobaid:{o.NameId}",
                        Text         = $"{o.Prijmeni} {o.Jmeno}{AppendTitle(o.TitulPred, o.TitulPo)}",
                        Priority     = o.Status == (int)Osoba.StatusOsobyEnum.Politik ? 2 : 0,
                        Type         = o.StatusOsoby().ToNiceDisplayName(),
                        ImageElement = $"<img src='{o.GetPhotoUrl(false)}' />",
                        Description  = InfoFact.RenderInfoFacts(
                            o.InfoFacts().Where(i => i.Level != InfoFact.ImportanceLevel.Stat).ToArray(),
                            2, true, false, "", "{0}", false)
                    };

                    synonyms[1]      = (Autocomplete)synonyms[0].MemberwiseClone();
                    synonyms[1].Text = $"{o.Jmeno} {o.Prijmeni}{AppendTitle(o.TitulPred, o.TitulPo)}";

                    lock (_loadPlock)
                    {
                        results.Add(synonyms[0]);
                        results.Add(synonyms[1]);
                    }

                    return(new Devmasters.Batch.ActionOutputData());
                }
                                                                , true
                                                                );
            }
            return(results);
        }
Esempio n. 11
0
        private static Sponzoring FindDuplicate(Sponzoring sponzoring, DbEntities db)
        {
            // u sponzoringu nekontrolujeme organizaci, ani rok, protože to není historicky konzistentní
            var result = db.Sponzoring.Where(s => s.Id == sponzoring.Id).FirstOrDefault();

            if (result != null)
            {
                return(result);
            }

            return(db.Sponzoring
                   .Where(s =>
                          s.IcoDarce == sponzoring.IcoDarce &&
                          s.IcoPrijemce == sponzoring.IcoPrijemce &&
                          s.OsobaIdDarce == sponzoring.OsobaIdDarce &&
                          s.OsobaIdPrijemce == sponzoring.OsobaIdPrijemce &&
                          s.Typ == sponzoring.Typ &&
                          s.Hodnota == sponzoring.Hodnota &&
                          s.DarovanoDne == sponzoring.DarovanoDne
                          )
                   .FirstOrDefault());
        }
Esempio n. 12
0
        public static InvoiceItems.ShopItem?GetCurrentOrderForUser(string userId)
        {
            DateTime now    = DateTime.Now.Date;
            DateTime now_30 = DateTime.Now.Date.AddDays(-30);

            using (DbEntities db = new DbEntities())
            {
                var items = db.Invoices
                            .Where(m => m.ID_Customer == userId && (m.Status == 3 || m.Created > now_30))
                            .Join(db.InvoiceItems.Where(ii => ii.Expires > now),
                                  inv => inv.ID,
                                  ii => ii.ID_Invoice, (inv, ii) => ii)
                            .OrderByDescending(ii => ii.ID_ShopItem);

                if (items.Count() > 0)
                {
                    return((InvoiceItems.ShopItem)items.First().ID_ShopItem);
                }
                else
                {
                    return(null);
                }
            }
        }
Esempio n. 13
0
        public static void ResetTask(int taskItemId, bool decreasePriority = true)
        {
            using (DbEntities db = new DbEntities())
            {
                ItemToOcrQueue i = db.ItemToOcrQueue.Where(m => m.pk == taskItemId).FirstOrDefault();
                if (i != null)
                {
                    i.done = null;

                    i.started = null;
                    i.success = null;
                    i.result  = null;
                    if (decreasePriority)
                    {
                        i.priority--;
                        if (i.priority < 1)
                        {
                            i.priority = 1;
                        }
                    }
                    db.SaveChanges();
                }
            }
        }
Esempio n. 14
0
        public static void AddOrUpdate(
            int osobaId, string dcerinkaIco,
            int kod_angm, string funkce, decimal?share, DateTime?fromDate, DateTime?toDate, string zdroj = ""
            )
        {
            using (Lib.Data.DbEntities db = new DbEntities())
            {
                var existing = db.OsobaVazby
                               .Where(m =>
                                      m.OsobaID == osobaId &&
                                      m.VazbakICO == dcerinkaIco &&
                                      m.DatumOd == fromDate &&
                                      m.DatumDo == toDate
                                      )
                               .FirstOrDefault();
                if (existing == null)
                {
                    existing = db.OsobaVazby
                               .Where(m =>
                                      m.OsobaID == osobaId &&
                                      m.VazbakICO == dcerinkaIco &&
                                      m.DatumOd == fromDate
                                      )
                               .FirstOrDefault();
                }

                if (existing != null)
                {
                    //update
                    existing.TypVazby         = kod_angm;
                    existing.PojmenovaniVazby = funkce;
                    if (existing.podil != share)
                    {
                        existing.podil = share;
                    }
                    if (existing.DatumOd != fromDate)
                    {
                        existing.DatumOd = fromDate;
                    }
                    if (existing.DatumDo != toDate)
                    {
                        existing.DatumDo = toDate;
                    }
                    existing.LastUpdate = DateTime.Now;
                }
                else //new
                {
                    OsobaVazby af = new OsobaVazby();
                    af.OsobaID          = osobaId;
                    af.VazbakICO        = dcerinkaIco;
                    af.DatumOd          = fromDate;
                    af.DatumDo          = toDate;
                    af.TypVazby         = kod_angm;
                    af.PojmenovaniVazby = funkce;
                    af.podil            = share;
                    af.LastUpdate       = DateTime.Now;
                    db.OsobaVazby.Add(af);
                }
                db.SaveChanges();
            }
        }
Esempio n. 15
0
        public static void AddOrUpdate(
            int osobaId, int vazbakOsobaId,
            int kod_angm, string funkce, decimal?share, DateTime?fromDate, DateTime?toDate, string zdroj = ""
            )
        {
            using (Lib.Data.DbEntities db = new DbEntities())
            {
                var existing = db.OsobaVazby
                               .Where(m =>
                                      m.OsobaID == osobaId &&
                                      m.VazbakOsobaId == vazbakOsobaId &&
                                      m.DatumOd == fromDate &&
                                      m.DatumDo == toDate
                                      )
                               .FirstOrDefault();
                if (existing == null)
                {
                    existing = db.OsobaVazby
                               .Where(m =>
                                      m.OsobaID == osobaId &&
                                      m.VazbakOsobaId == vazbakOsobaId &&
                                      m.DatumOd == fromDate
                                      )
                               .FirstOrDefault();
                }

                if (existing != null)
                {
                    //update
                    existing.TypVazby         = kod_angm;
                    existing.PojmenovaniVazby = funkce;

                    if (existing.podil != share)
                    {
                        existing.podil = share;
                    }
                    if (existing.DatumOd != fromDate)
                    {
                        existing.DatumOd = fromDate;
                    }
                    if (existing.DatumDo != toDate)
                    {
                        existing.DatumDo = toDate;
                    }
                    existing.LastUpdate = DateTime.Now;
                }
                else //new
                {
                    OsobaVazby af = new OsobaVazby();
                    af.OsobaID          = osobaId;
                    af.VazbakICO        = "";
                    af.VazbakOsobaId    = vazbakOsobaId;
                    af.DatumOd          = fromDate;
                    af.DatumDo          = toDate;
                    af.TypVazby         = kod_angm;
                    af.PojmenovaniVazby = funkce;
                    af.podil            = share;
                    af.LastUpdate       = DateTime.Now;
                    db.OsobaVazby.Add(af);
                }
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    HlidacStatu.Util.Consts.Logger.Error("", e);
                    throw;
                }
            }
        }
        private static Sponzoring CreateSponzoring(Sponzoring sponzoring, string user, DbEntities db)
        {
            if (sponzoring.OsobaIdDarce == 0 &&
                string.IsNullOrWhiteSpace(sponzoring.IcoDarce))
            {
                throw new Exception("Cant attach sponzoring to a person or to a company since their reference is empty");
            }

            sponzoring.Created   = DateTime.Now;
            sponzoring.Edited    = DateTime.Now;
            sponzoring.UpdatedBy = user;

            db.Sponzoring.Add(sponzoring);
            db.SaveChanges();

            Audit.Add(Audit.Operations.Create, user, sponzoring, null);
            return(sponzoring);
        }
Esempio n. 17
0
        public ActionResult Watchdogs(string id, string wid, string disable, string enable, string delete)
        {
            string currWDtype = null;

            if (!string.IsNullOrEmpty(id))
            {
                if (WatchdogTypes.Any(w => w.ToLower() == id.ToLower()))
                {
                    currWDtype = id;
                }
            }
            //if (currWDtypes == null)
            //    currWDtypes = WatchdogTypes;

            List <WatchDog> wds = new List <WatchDog>();

            using (HlidacStatu.Lib.Data.DbEntities db = new HlidacStatu.Lib.Data.DbEntities())
            {
                string userid = this.User.Identity.GetUserId();

                if (!string.IsNullOrEmpty(wid))
                {
                    int watchdogid = Convert.ToInt32(wid);
                    HlidacStatu.Lib.Data.WatchDog wd;
                    wd = db.WatchDogs
                         .Where(m => m.Id == watchdogid && m.UserId == userid)
                         .FirstOrDefault();

                    if (wd == null)
                    {
                        return(View("Error404"));
                    }
                    else
                    {
                        if (disable == "1")
                        {
                            wd.StatusId = 0;
                            wd.Save();
                        }
                        if (enable == "1")
                        {
                            wd.StatusId = 1;
                            wd.Save();
                        }
                        if (delete == "1")
                        {
                            wd.Delete();
                        }

                        return(RedirectToAction("Watchdogs"));
                    }
                }
                else
                {
                    wds.AddRange(
                        db.WatchDogs.AsNoTracking()
                        .Where(m =>
                               (m.dataType == currWDtype || currWDtype == null) &&
                               m.UserId == userid)
                        );
                }
            }
            return(View(wds));
        }
        private static Sponzoring UpdateSponzoring(Sponzoring sponzoringToUpdate, Sponzoring sponzoring, string user, DbEntities db)
        {
            var sponzoringOriginal = sponzoringToUpdate.ShallowCopy();

            if (!string.IsNullOrWhiteSpace(sponzoring.IcoDarce))
            {
                sponzoringToUpdate.IcoDarce = sponzoring.IcoDarce;
            }
            if (sponzoring.OsobaIdDarce > 0)
            {
                sponzoringToUpdate.OsobaIdDarce = sponzoring.OsobaIdDarce;
            }

            sponzoringToUpdate.Edited    = DateTime.Now;
            sponzoringToUpdate.UpdatedBy = user;

            sponzoringToUpdate.DarovanoDne     = sponzoring.DarovanoDne;
            sponzoringToUpdate.Hodnota         = sponzoring.Hodnota;
            sponzoringToUpdate.IcoPrijemce     = sponzoring.IcoPrijemce;
            sponzoringToUpdate.OsobaIdPrijemce = sponzoring.OsobaIdPrijemce;
            sponzoringToUpdate.Popis           = sponzoring.Popis;
            sponzoringToUpdate.Typ             = sponzoring.Typ;
            sponzoringToUpdate.Zdroj           = sponzoring.Zdroj;

            db.SaveChanges();

            Audit.Add <Sponzoring>(Audit.Operations.Update, user, sponzoringToUpdate, sponzoringOriginal);
            return(sponzoringToUpdate);
        }
Esempio n. 19
0
        protected static UserOptions Get(string userId, ParameterType option, int?languageid)
        {
            var r = new DbEntities().UserOption_Get((int)option, userId, languageid);

            return((UserOptions)r.FirstOrDefault());
        }
Esempio n. 20
0
        public ActionResult AddWd(string query, string dataType, string name, int period, int focus)
        {
            using (HlidacStatu.Lib.Data.DbEntities db = new HlidacStatu.Lib.Data.DbEntities())
            {
                if (string.IsNullOrEmpty(query))
                {
                    return(Json("0", JsonRequestBehavior.AllowGet));
                }
                string id = this.User.Identity.GetUserId();

                var dt = dataType;

                HlidacStatu.Lib.Data.WatchDog wd = new HlidacStatu.Lib.Data.WatchDog();
                wd.Created    = DateTime.Now;
                wd.UserId     = id;
                wd.StatusId   = 1;
                wd.SearchTerm = query;
                wd.PeriodId   = period;
                wd.FocusId    = focus;
                wd.Name       = Devmasters.TextUtil.ShortenText(name, 50);
                if (dt.ToLower() == typeof(Smlouva).Name.ToLower())
                {
                    wd.dataType = typeof(Smlouva).Name;
                }
                else if (dt.ToLower() == typeof(VerejnaZakazka).Name.ToLower())
                {
                    wd.dataType = typeof(VerejnaZakazka).Name;
                }
                else if (dt.ToLower() == typeof(Lib.Data.Insolvence.Rizeni).Name.ToLower())
                {
                    wd.dataType = typeof(Lib.Data.Insolvence.Rizeni).Name;
                }
                else if (dt.ToLower().StartsWith(typeof(HlidacStatu.Lib.Data.External.DataSets.DataSet).Name.ToLower()))
                {
                    var dataSetId = dt.Replace("DataSet.", "");
                    if (HlidacStatu.Lib.Data.External.DataSets.DataSet.ExistsDataset(dataSetId) == false)
                    {
                        HlidacStatu.Util.Consts.Logger.Error("AddWd - try to hack, wrong dataType = " + dataType + "." + dataSetId);
                        throw new ArgumentOutOfRangeException("AddWd - try to hack, wrong dataType = " + dataType + "." + dataSetId);
                    }
                    wd.dataType = typeof(HlidacStatu.Lib.Data.External.DataSets.DataSet).Name + "." + dataSetId;
                }
                else if (dt == WatchDog.AllDbDataType)
                {
                    wd.dataType = dt;
                }
                else
                {
                    HlidacStatu.Util.Consts.Logger.Error("AddWd - try to hack, wrong dataType = " + dataType);
                    throw new ArgumentOutOfRangeException("AddWd - try to hack, wrong dataType = " + dataType);
                }
                if (!db.WatchDogs
                    .Any(m => m.dataType == wd.dataType && m.UserId == id && m.SearchTerm == query))
                {
                    wd.Save();
                }


                //var lastOrder = HlidacStatu.Lib.Data.Invoices.GetCurrentOrderForUser(this.User.Identity.GetUserId());
                //if (lastOrder.HasValue == false && focus == 1)
                //    return Json("2", JsonRequestBehavior.AllowGet);

                return(Json("1", JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 21
0
            private static void _SendWatchDogs(string datatype, string[] ids, string userid, string date, string specificemail, bool forceSend = false, Expression <Func <WatchDog, bool> > predicate = null)
            {
                HlidacStatu.Util.Consts.Logger.Info("Starting SendWatchDogs type:" + datatype);

                IEnumerable <int> watchdogs = null;

                using (Lib.Data.DbEntities db = new DbEntities())
                {
                    var data = db.WatchDogs.AsNoTracking()
                               .Where(m => m.StatusId > 0);


                    if (!string.IsNullOrEmpty(userid))
                    {
                        data = data.Where(m => m.UserId == userid);
                    }

                    if (!string.IsNullOrEmpty(datatype))
                    {
                        data = data.Where(m => m.dataType == datatype);
                    }

                    if (predicate != null)
                    {
                        data = data.Where(predicate);
                    }

                    if (ids != null)
                    {
                        data = data.Where(m => ids.Contains(m.Id.ToString()));
                    }

                    watchdogs = data
                                .Select(m => m.Id)
                                .ToArray();
                }


                System.Collections.Concurrent.ConcurrentBag <string> alreadySendInfo = new System.Collections.Concurrent.ConcurrentBag <string>();
                try
                {
                    Devmasters.Core.Batch.Manager.DoActionForAll <int, object>(watchdogs,
                                                                               (wdid, obj) =>
                    {
                        string log       = "";
                        var mainWatchdog = WatchDog.Load(wdid);
                        var mainWDBs     = WatchDog.GetWatchDogBase(mainWatchdog);

                        var notifResult = true;


                        foreach (var wdb in mainWDBs)
                        {
                            HlidacStatu.Util.Consts.Logger.Debug($"Starting watchdog {wdb.ToString()}");


                            var mainDatatype = wdb.OrigWD.dataType;
                            var user         = wdb.OrigWD.User();
                            if (user == null) //is not confirmed
                            {
                                var uuser = wdb.OrigWD.UnconfirmedUser();
                                wdb.OrigWD.DisableWDBySystem(DisabledBySystemReasons.NoConfirmedEmail,
                                                             alreadySendInfo.Contains(uuser.Id)
                                                             );
                                alreadySendInfo.Add(uuser.Id);
                                break;                                   //exit for
                            }
                            if (user != null && wdb.OrigWD.StatusId > 0) //check again, some of them could change to disabled
                            {
                                try
                                {
                                    notifResult = notifResult | _processIndividualWD(wdb, date, null, specificemail, forceSend);
                                }
                                catch (Exception e)
                                {
                                    HlidacStatu.Util.Consts.Logger.Error("WatchDog search error", e);
                                    log += "WatchDog search error " + e.ToString();
                                    //throw;
                                }
                            }
                        }
                        if (notifResult && date == null && forceSend == false)
                        {
                            DateTime toDate = WatchDogProcessor.DefaultRoundWatchdogTime(mainWatchdog.Period, DateTime.Now);

                            if (mainWatchdog.LastSearched.HasValue == false || mainWatchdog.LastSearched < toDate)
                            {
                                mainWatchdog.LastSearched = toDate;
                            }
                            mainWatchdog.RunCount++;
                            var latestRec = toDate;
                            if (mainWatchdog.LatestRec.HasValue == false)
                            {
                                mainWatchdog.LatestRec = latestRec;
                            }
                            else if (latestRec > mainWatchdog.LatestRec)
                            {
                                mainWatchdog.LatestRec = latestRec;
                            }

                            mainWatchdog.LastSent = mainWatchdog.LastSearched;

                            mainWatchdog.Save();
                        }



                        return(new Devmasters.Core.Batch.ActionOutputData()
                        {
                            CancelRunning = false, Log = log
                        });
                    },
                                                                               null,
                                                                               HlidacStatu.Util.Consts.outputWriter.OutputWriter,
                                                                               HlidacStatu.Util.Consts.progressWriter.ProgressWriter,
                                                                               System.Diagnostics.Debugger.IsAttached ? false : true);
                }
                catch (Exception e)
                {
                    HlidacStatu.Util.Consts.Logger.Fatal($"Watchdoga DoActionForAll error", e);
                }
            }
        public ActionResult Watchdog(string _id, string _dataid, string dataType = "VerejnaZakazka", string query = null, string expiration = null)
        {
            string id     = _id;
            string dataid = _dataid;

            id = id.ToLower();
            var apiAuth = Framework.ApiAuth.IsApiAuth(this,
                                                      parameters: new Framework.ApiCall.CallParameter[] {
                new Framework.ApiCall.CallParameter("id", id),
                new Framework.ApiCall.CallParameter("query", query),
                new Framework.ApiCall.CallParameter("expiration", expiration)
            });

            if (!apiAuth.Authentificated)
            {
                //Response.StatusCode = 401;
                return(Json(ApiResponseStatus.ApiUnauthorizedAccess, JsonRequestBehavior.AllowGet));
            }
            else
            {
                if (apiAuth.ApiCall.User != "*****@*****.**" &&
                    apiAuth.ApiCall.User != "*****@*****.**"
                    )
                {
                    return(Json(ApiResponseStatus.ApiUnauthorizedAccess, JsonRequestBehavior.AllowGet));
                }

                var wdName = WatchDog.APIID_Prefix + dataid;
                using (HlidacStatu.Lib.Data.DbEntities db = new HlidacStatu.Lib.Data.DbEntities())
                {
                    switch (id.ToLower())
                    {
                    case "add":
                        var expirDate = Devmasters.DT.Util.ToDateTime(expiration, "yyyy-MM-ddTHH:mm:ss");
                        if (string.IsNullOrEmpty(query))
                        {
                            return(Json(ApiResponseStatus.Error(-99, "No query"), JsonRequestBehavior.AllowGet));
                        }

                        var wd2 = db.WatchDogs.AsNoTracking().Where(m => m.Name == wdName).FirstOrDefault();
                        if (wd2 != null)
                        {
                            wd2.SearchTerm = query;
                            wd2.Expires    = expirDate;
                            wd2.Save();
                        }
                        else
                        {
                            var dt = dataType;

                            HlidacStatu.Lib.Data.WatchDog wd = new HlidacStatu.Lib.Data.WatchDog();
                            wd.Created         = DateTime.Now;
                            wd.UserId          = apiAuth.ApiCall.UserId;
                            wd.StatusId        = 1;
                            wd.SearchTerm      = query;
                            wd.PeriodId        = 2; //daily
                            wd.FocusId         = 0;
                            wd.Name            = wdName;
                            wd.Expires         = expirDate;
                            wd.SpecificContact = "HTTPPOSTBACK";
                            if (dt.ToLower() == typeof(Smlouva).Name.ToLower())
                            {
                                wd.dataType = typeof(Smlouva).Name;
                            }
                            else if (dt.ToLower() == typeof(VerejnaZakazka).Name.ToLower())
                            {
                                wd.dataType = typeof(VerejnaZakazka).Name;
                            }
                            else if (dt.ToLower().StartsWith(typeof(HlidacStatu.Lib.Data.External.DataSets.DataSet).Name.ToLower()))
                            {
                                var dataSetId = dt.Replace("DataSet.", "");
                                if (HlidacStatu.Lib.Data.External.DataSets.DataSet.ExistsDataset(dataSetId) == false)
                                {
                                    HlidacStatu.Util.Consts.Logger.Error("AddWd - try to hack, wrong dataType = " + dataType + "." + dataSetId);
                                    throw new ArgumentOutOfRangeException("AddWd - try to hack, wrong dataType = " + dataType + "." + dataSetId);
                                }
                                wd.dataType = typeof(HlidacStatu.Lib.Data.External.DataSets.DataSet).Name + "." + dataSetId;
                            }
                            else if (dt == WatchDog.AllDbDataType)
                            {
                                wd.dataType = dt;
                            }
                            else
                            {
                                HlidacStatu.Util.Consts.Logger.Error("AddWd - try to hack, wrong dataType = " + dataType);
                                throw new ArgumentOutOfRangeException("AddWd - try to hack, wrong dataType = " + dataType);
                            }

                            wd.Save();
                        }
                        break;

                    case "delete":
                    case "disable":
                    case "get":
                    case "enable":
                        var wd1 = db.WatchDogs.AsNoTracking().Where(m => m.Name == wdName).FirstOrDefault();
                        if (wd1 == null)
                        {
                            return(Json(ApiResponseStatus.Error(-404, "Watchdog not found"), JsonRequestBehavior.AllowGet));
                        }

                        if (id == "delete")
                        {
                            wd1.Delete();
                            return(Json(new { Ok = true }, JsonRequestBehavior.AllowGet));
                        }
                        if (id == "disable")
                        {
                            wd1.StatusId = 0;
                        }
                        if (id == "delete")
                        {
                            wd1.StatusId = 1;
                        }
                        if (id == "get")
                        {
                            return(Content(Newtonsoft.Json.JsonConvert.SerializeObject(new { id = wd1.Name.Replace("APIID:", ""), expiration = wd1.Expires, query = wd1.SearchTerm }), "text/json"));
                        }

                        wd1.Save();
                        break;

                    default:
                        break;
                    }
                }


                return(Json(new { Ok = true }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 23
0
        private static OsobaEvent UpdateEvent(OsobaEvent eventToUpdate, OsobaEvent osobaEvent, string user, DbEntities db)
        {
            if (eventToUpdate is null)
            {
                throw new ArgumentNullException(nameof(eventToUpdate), "Argument can't be null");
            }
            if (osobaEvent is null)
            {
                throw new ArgumentNullException(nameof(osobaEvent), "Argument can't be null");
            }
            if (db is null)
            {
                throw new ArgumentNullException(nameof(db), "Argument can't be null");
            }

            var eventOriginal = eventToUpdate.ShallowCopy();

            if (!string.IsNullOrWhiteSpace(osobaEvent.Ico))
            {
                eventToUpdate.Ico = osobaEvent.Ico;
            }
            if (osobaEvent.OsobaId > 0)
            {
                eventToUpdate.OsobaId = osobaEvent.OsobaId;
            }

            eventToUpdate.DatumOd    = osobaEvent.DatumOd;
            eventToUpdate.DatumDo    = osobaEvent.DatumDo;
            eventToUpdate.Organizace = ParseTools.NormalizaceStranaShortName(osobaEvent.Organizace);
            eventToUpdate.AddInfoNum = osobaEvent.AddInfoNum;
            eventToUpdate.AddInfo    = osobaEvent.AddInfo;
            eventToUpdate.Title      = osobaEvent.Title;
            eventToUpdate.Type       = osobaEvent.Type;
            eventToUpdate.Zdroj      = osobaEvent.Zdroj;
            eventToUpdate.Status     = osobaEvent.Status;
            eventToUpdate.CEO        = osobaEvent.CEO;
            eventToUpdate.Created    = DateTime.Now;

            db.SaveChanges();
            if (osobaEvent.OsobaId > 0)
            {
                Osoby.GetById.Get(osobaEvent.OsobaId).FlushCache();
            }
            Audit.Add(Audit.Operations.Update, user, eventToUpdate, eventOriginal);
            return(eventToUpdate);
        }
Esempio n. 24
0
        public static Invoices CreateNew(
            Lib.Data.InvoiceItems.ShopItem sluzba,
            string adresa,
            string mesto,
            string jmenoFirmy,
            string ICO,
            string jmenoOsoby,
            string DIC,
            string PSC,
            string userId,
            string username,
            bool sendEmail = true
            )
        {
            using (Lib.Data.DbEntities db = new DbEntities())
            {
                var obj = new Lib.Data.Invoices();
                obj.Address       = adresa;
                obj.City          = mesto;
                obj.Company       = jmenoFirmy;
                obj.CompanyID     = ICO;
                obj.Country       = "CZ";
                obj.Created       = DateTime.Now;
                obj.FirstName     = jmenoOsoby;
                obj.InvoiceNumber = (db.Invoices.Count() + 1).ToString();
                obj.Status        = (int)Lib.Data.Invoices.InvoiceStatus.New;
                obj.Text          = "Služby serveru HlidacStatu.cz";
                obj.VatID         = DIC;
                obj.Zip           = PSC;
                obj.ID_Customer   = userId;
                var ii = new InvoiceItems()
                {
                    ID_ShopItem = (int)sluzba,
                    Expires     = DateTime.Now.AddYears(1),
                    Name        = "HlidacStatu.cz - " + sluzba.ToNiceDisplayName(),
                    Invoices    = obj,
                    VAT         = 1.21m,
                    Created     = DateTime.Now,
                };
                switch (sluzba)
                {
                case Lib.Data.InvoiceItems.ShopItem.Zakladni:
                    ii.Price = 14900;
                    break;

                case Lib.Data.InvoiceItems.ShopItem.Kompletni:
                    ii.Price = 29900;
                    break;

                case Lib.Data.InvoiceItems.ShopItem.NGO:
                default:
                    ii.Price = 0;
                    break;
                }

                obj.InvoiceItems = new InvoiceItems[] { ii };

                db.Invoices.Add(obj);
                db.InvoiceItems.Add(ii);

                if (sendEmail)
                {
                    try
                    {
                        using (MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**"))
                        {
                            using (SmtpClient smtp = new SmtpClient())
                            {
                                msg.Subject = "Objednavka " + sluzba.ToNiceDisplayName();
                                msg.Body    = @"ico:" + ICO + "\n"
                                              + "firma:" + jmenoFirmy + "\n"
                                              + "jmeno:" + jmenoOsoby + "\n"
                                              + "email:" + username + "\n"
                                              + "userid:" + userId + "\n"
                                ;
                                msg.BodyEncoding    = System.Text.Encoding.UTF8;
                                msg.SubjectEncoding = System.Text.Encoding.UTF8;

                                HlidacStatu.Util.Consts.Logger.Info("Sending email to " + msg.To);
                                //msg.Bcc.Add("*****@*****.**");
                                smtp.Send(msg);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        HlidacStatu.Util.Consts.Logger.Error("Send email", e);
                    }
                }
                db.SaveChanges();
                return(obj);
            }
        }