public static int UserRegistration(ThisUser entity, string ipAddress, string type, string extra = "")
        {
            string server = UtilityManager.GetAppKeyValue("serverName", "");

            SiteActivity log = new SiteActivity();

            log.CreatedDate  = System.DateTime.Now;
            log.ActivityType = "Audit";
            log.Activity     = "Account";
            log.Event        = type;
            log.Comment      = string.Format("{0} ({1}) {4}. From IPAddress: {2}, on server: {3}. {5}", entity.FullName(), entity.Id, ipAddress, server, type, extra);
            //actor type - person, system
            log.ActionByUserId = entity.Id;
            log.TargetUserId   = entity.Id;
            log.SessionId      = ActivityManager.GetCurrentSessionId();
            try
            {
                return(new ActivityManager().SiteActivityAdd(log));
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".UserRegistrationFromPortal()");
                return(0);
            }
        }
        public static int UserRegistrationConfirmation(ThisUser entity, string type)
        {
            string server = UtilityManager.GetAppKeyValue("serverName", "");
            //EFDAL.IsleContentEntities ctx = new EFDAL.IsleContentEntities();
            SiteActivity log = new SiteActivity();

            try
            {
                log.CreatedDate  = System.DateTime.Now;
                log.ActivityType = "Audit";
                log.Activity     = "Account";
                log.Event        = "Confirmation";
                log.Comment      = string.Format("{0} ({1}) Registration Confirmation, on server: {2}, tyep: {3}", entity.FullName(), entity.Id, server, type);
                //actor type - person, system
                log.ActionByUserId = entity.Id;
                log.TargetUserId   = entity.Id;

                log.SessionId = ActivityManager.GetCurrentSessionId();

                return(new ActivityManager().SiteActivityAdd(log));
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".UserRegistrationConfirmation()");
                return(0);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 添加活动信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int SaveActivity(SiteActivity model)
        {
            string sql = @"INSERT INTO [ACT_SiteActivity]
                        ([ID]
                       ,[SiteCode]
                       ,[ActTitle]
                       ,[Photo]
                       ,[ActContent]
                       ,[ActType]
                       ,[ActStatus]
                       ,[StartTime]
                       ,[EndTime]
                       ,[CutOffTime]
                       ,[Discount]
                       ,[OpenTime]
                       ,[CloseTime]
                       ,[DayLimit]
                       ,[Remark]
                       ,[AddTime])
                 VALUES
                        (@ID
                       ,@SiteCode
                       ,@ActTitle
                       ,@Photo
                       ,@ActContent
                       ,@ActType
                       ,@ActStatus
                       ,@StartTime
                       ,@EndTime
                       ,@CutOffTime
                       ,@Discount
                       ,@OpenTime
                       ,@CloseTime
                       ,@DayLimit
                       ,@Remark
                       ,@AddTime)";

            System.Data.SqlClient.SqlParameter[] paras = new System.Data.SqlClient.SqlParameter[]
            {
                new System.Data.SqlClient.SqlParameter("@ID", model.ID),
                new System.Data.SqlClient.SqlParameter("@SiteCode", model.SiteCode),
                new System.Data.SqlClient.SqlParameter("@ActTitle", model.ActTitle),
                new System.Data.SqlClient.SqlParameter("@Photo", model.Photo),
                new System.Data.SqlClient.SqlParameter("@ActContent", model.ActContent),
                new System.Data.SqlClient.SqlParameter("@ActType", model.ActType),
                new System.Data.SqlClient.SqlParameter("@ActStatus", model.ActStatus),
                new System.Data.SqlClient.SqlParameter("@StartTime", model.StartTime),
                new System.Data.SqlClient.SqlParameter("@EndTime", model.EndTime),
                new System.Data.SqlClient.SqlParameter("@CutOffTime", model.CutOffTime),
                new System.Data.SqlClient.SqlParameter("@Discount", model.DisCount),
                new System.Data.SqlClient.SqlParameter("@OpenTime", model.OpenTime),
                new System.Data.SqlClient.SqlParameter("@CloseTime", model.CloseTime),
                new System.Data.SqlClient.SqlParameter("@DayLimit", model.DayLimit),
                new System.Data.SqlClient.SqlParameter("@Remark", model.Remark),
                new System.Data.SqlClient.SqlParameter("@AddTime", DateTime.Now)
            };
            return(DbHelperSQL.ExecuteSql(sql, paras));
        }
Exemplo n.º 4
0
 public void AddSiteActivity(SiteActivityInfo info)
 {
     if (info == null)
     {
         throw new Exception("当前广告信息无效!");
     }
     using (var manager = new SiteActivityManager())
     {
         SiteActivity entity = new SiteActivity();
         ObjectConvert.ConverInfoToEntity(info, ref entity);
         manager.AddSiteActivity(entity);
     }
 }
Exemplo n.º 5
0
        public static int SiteActivityAdd(string activityType, string activity, string eventType, string comment
                                          , int actionByUserId, int targetUserId, int activityObjectId
                                          , string sessionId = "", string ipAddress = "")
        {
            string       server = UtilityManager.GetAppKeyValue("serverName", "");
            SiteActivity log    = new SiteActivity();

            if (sessionId == null || sessionId.Length < 10)
            {
                sessionId = HttpContext.Current.Session.SessionID;
            }

            if (ipAddress == null || ipAddress.Length < 10)
            {
                ipAddress = ActivityManager.GetUserIPAddress();
            }

            try
            {
                log.CreatedDate  = System.DateTime.Now;
                log.ActivityType = activityType;
                log.Activity     = activity;
                log.Event        = eventType;
                log.Comment      = comment;
                //actor type - person, system
                if (actionByUserId > 0)
                {
                    log.ActionByUserId = actionByUserId;
                }
                if (targetUserId > 0)
                {
                    log.TargetUserId = targetUserId;
                }
                if (activityObjectId > 0)
                {
                    log.ActivityObjectId = activityObjectId;
                }

                log.SessionId = sessionId;
                log.IPAddress = ipAddress;

                return(new ActivityManager().SiteActivityAdd(log));
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".SiteActivityAdd()");
                return(0);
            }
        }         //
        } //

        private void MapToDB(SiteActivity from, ActivityLog to)
        {
            to.Id               = from.Id;
            to.ActivityType     = from.ActivityType;
            to.Activity         = from.Activity;
            to.Event            = from.Event;
            to.Comment          = from.Comment;
            to.TargetUserId     = from.TargetUserId;
            to.ActionByUserId   = from.ActionByUserId;
            to.ActivityObjectId = from.ActivityObjectId;
            to.ObjectRelatedId  = from.ObjectRelatedId;

            to.RelatedTargetUrl = from.RelatedTargetUrl;
            to.TargetObjectId   = from.TargetObjectId;
            to.SessionId        = from.SessionId;
            to.IPAddress        = from.IPAddress;
            to.Referrer         = from.Referrer;
            to.IsBot            = from.IsBot;
        }
Exemplo n.º 7
0
        public void ShowActivityInfo(string strID)
        {
            SiteActivityDAL dal   = new SiteActivityDAL();
            DataSet         ds    = dal.GetActivityDetail(strID);
            SiteActivity    model = DataConvert.DataRowToModel <SiteActivity>(ds.Tables[0].Rows[0]);

            this.txtName.Text     = model.ActTitle;
            this.hd_content.Value = model.ActContent;
            this.txtSummary.Text  = model.Remark;
            starttime.Text        = model.StartTime;
            endtime.Text          = model.EndTime;
            cutTime.Text          = model.CutOffTime;
            Discount.Text         = model.DisCount;
            opentime.Text         = model.OpenTime;
            closetime.Text        = model.CloseTime;
            daylimit.Text         = model.DayLimit.ToString();
            if (model.ActStatus == 0)
            {
                ActStatusno.Checked = true;
            }
            else
            {
                ActStatusyes.Checked = true;
            }
            img0.Src = "../../" + model.Photo;
            if (strAction == "show")
            {
                this.btnReset.Visible = false;
                this.btnSave.Visible  = false;
                starttime.ReadOnly    = true;
                endtime.ReadOnly      = true;
                txtName.ReadOnly      = true;
                txtSummary.ReadOnly   = true;
            }
            else
            {
                starttime.Attributes.Add("onclick", "WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})");
                endtime.Attributes.Add("onclick", "WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})");
                cutTime.Attributes.Add("onclick", "WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})");
                opentime.Attributes.Add("onclick", "WdatePicker({dateFmt:'HH:mm:ss'})");
                closetime.Attributes.Add("onclick", "WdatePicker({dateFmt:'HH:mm:ss'})");
            }
        }
        private static void MapFromDB(ActivityLog from, SiteActivity to)
        {
            to.Id               = from.Id;
            to.Created          = (DateTime)from.CreatedDate;
            to.ActivityType     = from.ActivityType;
            to.Activity         = from.Activity;
            to.Event            = from.Event;
            to.Comment          = from.Comment;
            to.TargetUserId     = from.TargetUserId;
            to.ActionByUserId   = from.ActionByUserId;
            to.ActivityObjectId = from.ActivityObjectId;
            to.ObjectRelatedId  = from.ObjectRelatedId;

            to.RelatedTargetUrl = from.RelatedTargetUrl;
            to.TargetObjectId   = from.TargetObjectId;
            to.SessionId        = from.SessionId;
            to.IPAddress        = from.IPAddress;
            to.Referrer         = from.Referrer;
            to.IsBot            = from.IsBot;
        }
        public static SiteActivity GetLastImport()
        {
            SiteActivity entity = new SiteActivity();

            using (var context = new EntityContext())
            {
                List <ActivityLog> list = context.ActivityLog
                                          .Where(s => s.ActivityType == "System" &&
                                                 s.Activity == "Import" &&
                                                 s.Event == "Start")
                                          .OrderByDescending(o => o.CreatedDate)
                                          .Take(1)
                                          .ToList();
                if (list != null && list.Count > 0)
                {
                    ActivityLog efentity = list[0];
                    MapFromDB(efentity, entity);
                }
            }
            return(entity);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Add site activity
        /// </summary>
        /// <param name="log"></param>
        public void AddActivity(SiteActivity log)
        {
            if (log.SessionId == null || log.SessionId.Length < 10)
            {
                log.SessionId = ActivityManager.GetCurrentSessionId();
            }

            if (log.IPAddress == null || log.IPAddress.Length < 10)
            {
                log.IPAddress = ActivityManager.GetUserIPAddress();
            }

            try
            {
                mgr.SiteActivityAdd(log);
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".AddActivity(SiteActivity log)");
                return;
            }
        }
Exemplo n.º 11
0
        public void UpdateSiteActivity(SiteActivityInfo info)
        {
            if (info == null || info.Id <= 0)
            {
                throw new Exception("当前活动信息无效!");
            }
            using (var manager = new SiteActivityManager())
            {
                SiteActivity entity = new SiteActivity();
                entity = manager.QuerySiteActivity(info.Id);
                if (entity == null)
                {
                    throw new Exception("未查询到活动信息!");
                }
                entity.ArticleUrl = info.ArticleUrl;
                //entity.ImageUrl = info.ImageUrl;
                entity.Titile    = info.Titile;
                entity.StartTime = info.StartTime;
                entity.EndTime   = info.EndTime;

                manager.UpdateSiteActivity(entity);
            }
        }
Exemplo n.º 12
0
        private static int UserAuthentication(ThisUser entity, string type)
        {
            string       server = UtilityManager.GetAppKeyValue("serverName", "");
            SiteActivity log    = new SiteActivity();

            log.CreatedDate  = System.DateTime.Now;
            log.ActivityType = "Audit";
            log.Activity     = "Account";
            log.Event        = "Authentication: " + type;
            log.Comment      = string.Format("{0} ({1}) logged in ({2}) on server: {3}", entity.FullName(), entity.Id, type, server);
            //actor type - person, system
            log.ActionByUserId = entity.Id;
            log.TargetUserId   = entity.Id;
            log.SessionId      = ActivityManager.GetCurrentSessionId();
            try
            {
                return(new ActivityManager().SiteActivityAdd(log));
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".UserAuthentication()");
                return(0);
            }
        }
Exemplo n.º 13
0
        /// <remarks>
        /// Sample XML:
        /// http://code.google.com/apis/checkout/developer/Google_Checkout_XML_API_Notification_API.html#new_order_notifications
        /// </remarks>
        public void ProcessRequest(HttpContext context)
        {
            string googleXml = EncodeHelper.Utf8StreamToString(context.Request.InputStream);

            SiteActivity.Log(SiteActivity.Types.GoogleNotification);

            if (!string.IsNullOrEmpty(googleXml))
            {
                StreamWriter file = null;
                try {
                    string fileName = string.Format("{0}-{1}-{2}.xml",
                                                    EncodeHelper.GetTopElement(googleXml),
                                                    EncodeHelper.GetElementValue(googleXml, "google-order-number"),
                                                    EncodeHelper.GetElementValue(googleXml, "serial-number"));
                    string path = string.Format("{0}/google/{1}",
                                                Data.File.DataFolder, fileName);
                    file = new StreamWriter(path, false, Encoding.UTF8);
                    file.Write(googleXml);
                    SiteActivity.Log(SiteActivity.Types.GoogleFileSave, path);
                } catch (System.Exception e) {
                    Idaho.Exception.Log(e, Exception.Types.Google, googleXml);
                    context.Response.StatusCode = 500;
                } finally {
                    if (file != null)
                    {
                        file.Close();
                    }
                }
            }
            else
            {
                context.Response.Redirect("./", true);
            }
            context.Response.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            context.Response.Write("<notification-acknowledgment xmlns=\"http://checkout.google.com/schema/2\"/>");
        }
        public static List <SiteActivity> SearchToday(BaseSearchModel parms)
        {
            string              connectionString = DBConnectionRO();
            SiteActivity        entity           = new SiteActivity();
            List <SiteActivity> list             = new List <SiteActivity>();

            if (parms.PageSize == 0)
            {
                parms.PageSize = 25;
            }
            int skip = 0;

            if (parms.PageNumber > 1)
            {
                skip = (parms.PageNumber - 1) * parms.PageSize;
            }
            if (string.IsNullOrWhiteSpace(parms.OrderBy))
            {
                parms.OrderBy      = "CreatedDate";
                parms.IsDescending = true;
            }
            list = SearchAll(parms);
            return(list);
        } //
Exemplo n.º 15
0
        /// <summary>
        /// Persist ConditionManifest
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="parentUid"></param>
        /// <param name="userId"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity, ref SaveStatus status)
        {
            bool isValid = true;

            //will not have a parent Guid - should be the entity.OwningAgentUid
            //Guid parentUid = entity.OwningAgentUid;

            if (!IsValidGuid(entity.OwningAgentUid))
            {
                status.AddError("Error: the parent identifier was not provided.");
                return(false);
            }

            int count = 0;

            DBEntity efEntity    = new DBEntity();
            int      parentOrgId = 0;

            Guid   condtionManifestParentUid = new Guid();
            Entity parent = EntityManager.GetEntity(entity.OwningAgentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddError("Error - the entity for the parent organization was not found.");
                return(false);
            }
            if (parent.EntityTypeId == CodesManager.ENTITY_TYPE_ORGANIZATION)
            {
                parentOrgId = parent.EntityBaseId;
                condtionManifestParentUid = parent.EntityUid;
                //no common condition in this context
            }


            using (var context = new EntityContext())
            {
                try
                {
                    bool isEmpty = false;

                    if (ValidateProfile(entity, ref isEmpty, ref status) == false)
                    {
                        return(false);
                    }
                    if (isEmpty)
                    {
                        status.AddWarning("The Condition Manifest Profile is empty. ");
                        return(false);
                    }

                    if (entity.Id == 0)
                    {
                        //add
                        efEntity = new DBEntity();
                        MapToDB(entity, efEntity);

                        efEntity.OrganizationId = parentOrgId;
                        efEntity.EntityStateId  = 3;
                        efEntity.Created        = efEntity.LastUpdated = DateTime.Now;

                        if (IsValidGuid(entity.RowId))
                        {
                            efEntity.RowId = entity.RowId;
                        }
                        else
                        {
                            efEntity.RowId = Guid.NewGuid();
                        }

                        context.ConditionManifest.Add(efEntity);
                        count = context.SaveChanges();

                        entity.Id    = efEntity.Id;
                        entity.RowId = efEntity.RowId;
                        if (count == 0)
                        {
                            status.AddError(" Unable to add Condition Manifest Profile");
                        }
                        else
                        {
                            //create the Entity.ConditionManifest
                            //ensure to handle this properly when adding a commonCondition CM to a CM
                            Entity_HasConditionManifest_Add(condtionManifestParentUid, efEntity.Id, ref status);

                            if (!UpdateParts(entity, ref status))
                            {
                                isValid = false;
                            }

                            SiteActivity sa = new SiteActivity()
                            {
                                ActivityType     = "ConditionManifest",
                                Activity         = "Import",
                                Event            = "Add",
                                Comment          = string.Format("ConditionManifest was added by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                                ActivityObjectId = entity.Id
                            };
                            new ActivityManager().SiteActivityAdd(sa);
                            // a trigger is used to create the entity Object.
                        }
                    }
                    else
                    {
                        efEntity = context.ConditionManifest.SingleOrDefault(s => s.Id == entity.Id);
                        if (efEntity != null && efEntity.Id > 0)
                        {
                            //delete the entity and re-add
                            //Entity e = new Entity()
                            //{
                            //	EntityBaseId = efEntity.Id,
                            //	EntityTypeId = CodesManager.ENTITY_TYPE_CONDITION_MANIFEST,
                            //	EntityType = "ConditionManifest",
                            //	EntityUid = efEntity.RowId,
                            //	EntityBaseName = efEntity.Name
                            //};
                            //if ( entityMgr.ResetEntity( e, ref statusMessage ) )
                            //{

                            //}

                            entity.RowId = efEntity.RowId;
                            //update
                            MapToDB(entity, efEntity);
                            //assume and validate, that if we get here we have a full record
                            if ((efEntity.EntityStateId ?? 1) == 1)
                            {
                                efEntity.EntityStateId = 3;
                            }

                            //has changed?
                            if (HasStateChanged(context))
                            {
                                efEntity.LastUpdated = System.DateTime.Now;

                                count = context.SaveChanges();
                            }
                            else
                            {
                                //update entity.LastUpdated - assuming there has to have been some change in related data
                                new EntityManager().UpdateModifiedDate(entity.RowId, ref status);
                            }

                            if (!UpdateParts(entity, ref status))
                            {
                                isValid = false;
                            }

                            SiteActivity sa = new SiteActivity()
                            {
                                ActivityType     = "ConditionManifest",
                                Activity         = "Import",
                                Event            = "Update",
                                Comment          = string.Format("ConditionManifest was updated by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                                ActivityObjectId = entity.Id
                            };
                            new ActivityManager().SiteActivityAdd(sa);
                        }
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Save() ", "ConditionManifest");
                    status.AddError("Error - the save was not successful. " + message);
                    LoggingHelper.LogError(dbex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                    isValid = false;
                }
                catch (Exception ex)
                {
                    string message = FormatExceptions(ex);
                    status.AddError("Error - the save was not successful. " + message);
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                    isValid = false;
                }
            }



            return(isValid);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Add/Update a CompetencyFramework
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity,
                         ref SaveStatus status, bool addingActivity = false)
        {
            bool isValid = true;
            int  count   = 0;

            DBEntity efEntity = new DBEntity();

            try
            {
                using (var context = new EntityContext())
                {
                    if (ValidateProfile(entity, ref status) == false)
                    {
                        return(false);
                    }

                    if (entity.Id == 0)
                    {
                        //add
                        efEntity = new DBEntity();
                        MapToDB(entity, efEntity);

                        if (IsValidDate(status.EnvelopeCreatedDate))
                        {
                            efEntity.Created = status.LocalCreatedDate;
                        }
                        else
                        {
                            efEntity.Created = DateTime.Now;
                        }
                        //
                        if (IsValidDate(status.EnvelopeUpdatedDate))
                        {
                            efEntity.LastUpdated = status.LocalUpdatedDate;
                        }
                        else
                        {
                            efEntity.LastUpdated = DateTime.Now;
                        }

                        if (IsValidGuid(entity.RowId))
                        {
                            efEntity.RowId = entity.RowId;
                        }
                        else
                        {
                            efEntity.RowId = Guid.NewGuid();
                        }

                        context.CompetencyFramework.Add(efEntity);

                        count = context.SaveChanges();

                        entity.Id    = efEntity.Id;
                        entity.RowId = efEntity.RowId;
                        if (count == 0)
                        {
                            status.AddWarning(string.Format(" Unable to add Profile: {0} <br\\> ", string.IsNullOrWhiteSpace(entity.Name) ? "no description" : entity.Name));
                        }
                        else
                        {
                            if (addingActivity)
                            {
                                //add log entry
                                SiteActivity sa = new SiteActivity()
                                {
                                    ActivityType     = "CompetencyFramework",
                                    Activity         = "Import",
                                    Event            = "Add",
                                    Comment          = string.Format("New Competency Framework was found by the import. Name: {0}, URI: {1}", entity.Name, entity.FrameworkUri),
                                    ActivityObjectId = entity.Id
                                };
                                new ActivityManager().SiteActivityAdd(sa);
                            }
                        }
                    }
                    else
                    {
                        efEntity = context.CompetencyFramework.FirstOrDefault(s => s.Id == entity.Id);
                        if (efEntity != null && efEntity.Id > 0)
                        {
                            entity.RowId = efEntity.RowId;
                            //update
                            MapToDB(entity, efEntity);

                            //need to do the date check here, or may not be updated
                            if (IsValidDate(status.EnvelopeCreatedDate) && status.LocalCreatedDate < efEntity.Created)
                            {
                                efEntity.Created = status.LocalCreatedDate;
                            }
                            if (IsValidDate(status.EnvelopeUpdatedDate) && status.LocalUpdatedDate != efEntity.LastUpdated)
                            {
                                efEntity.LastUpdated = status.LocalUpdatedDate;
                            }
                            //has changed?
                            if (HasStateChanged(context))
                            {
                                if (IsValidDate(status.EnvelopeUpdatedDate))
                                {
                                    efEntity.LastUpdated = status.LocalUpdatedDate;
                                }
                                else
                                {
                                    efEntity.LastUpdated = DateTime.Now;
                                }

                                count = context.SaveChanges();
                                if (addingActivity)
                                {
                                    //add log entry
                                    SiteActivity sa = new SiteActivity()
                                    {
                                        ActivityType     = "CompetencyFramework",
                                        Activity         = "Import",
                                        Event            = "Update",
                                        Comment          = string.Format("Updated Competency Framework found by the import. Name: {0}, URI: {1}", entity.Name, entity.FrameworkUri),
                                        ActivityObjectId = entity.Id
                                    };
                                    new ActivityManager().SiteActivityAdd(sa);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, "CompetencyFrameworkManager.Save()");
            }

            return(isValid);
        }
Exemplo n.º 17
0
        /// <summary>
        /// add a HoldersProfile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private int Add(ThisEntity entity, Entity parentEntity, ref SaveStatus status)
        {
            DBEntity efEntity = new DBEntity();

            using (var context = new EntityContext())
            {
                try
                {
                    MapToDB(entity, efEntity);

                    if (IsValidGuid(entity.RowId))
                    {
                        efEntity.RowId = entity.RowId;
                    }
                    else
                    {
                        efEntity.RowId = Guid.NewGuid();
                    }
                    efEntity.EntityStateId = 3;
                    //the envelope date may not reflect when the earning profile was added
                    //if ( IsValidDate( status.EnvelopeCreatedDate ) )
                    //{
                    //	efEntity.Created = status.LocalCreatedDate;
                    //	efEntity.LastUpdated = status.LocalCreatedDate;
                    //}
                    //else
                    {
                        efEntity.Created     = System.DateTime.Now;
                        efEntity.LastUpdated = System.DateTime.Now;
                    }

                    context.HoldersProfile.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        entity.Id    = efEntity.Id;
                        entity.RowId = efEntity.RowId;
                        //add log entry
                        SiteActivity sa = new SiteActivity()
                        {
                            ActivityType     = "HoldersProfile",
                            Activity         = "Import",
                            Event            = "Add",
                            Comment          = string.Format("Full HoldersProfile was added by the import. CTID: {0}, Desc: {1}", entity.CTID, entity.Description),
                            ActivityObjectId = entity.Id
                        };
                        new ActivityManager().SiteActivityAdd(sa);

                        new Entity_HoldersProfileManager().Add(parentEntity.EntityUid, entity.Id, ref status);
                        if (UpdateParts(entity, ref status) == false)
                        {
                        }

                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error

                        string message = thisClassName + string.Format(". Add Failed", "Attempted to add a HoldersProfile. The process appeared to not work, but was not an exception, so we have no message, or no clue. HoldersProfile: {0}, ctid: {1}", entity.Name, entity.CTID);
                        status.AddError(thisClassName + ". Error - the add was not successful. " + message);
                        EmailManager.NotifyAdmin("HoldersProfileManager. Add Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "HoldersProfile");
                    status.AddError(thisClassName + ".Add(). Error - the save was not successful. " + message);

                    LoggingHelper.LogError(message, true);
                }
                catch (Exception ex)
                {
                    string message = FormatExceptions(ex);
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Add(), CTID: {0}\r\n", efEntity.CTID));
                    status.AddError(thisClassName + ".Add(). Error - the save was not successful. \r\n" + message);
                }
            }

            return(efEntity.Id);
        }
Exemplo n.º 18
0
        public bool Save(ThisEntity entity, Entity parentEntity, ref SaveStatus status)
        {
            bool isValid = true;
            int  count   = 0;

            try
            {
                using (var context = new EntityContext())
                {
                    if (ValidateProfile(entity, ref status) == false)
                    {
                        //return false;
                    }
                    //actually will always be an add
                    if (entity.Id > 0)
                    {
                        //TODO - consider if necessary, or interferes with anything
                        context.Configuration.LazyLoadingEnabled = false;
                        DBEntity efEntity = context.HoldersProfile
                                            .FirstOrDefault(s => s.Id == entity.Id);

                        if (efEntity != null && efEntity.Id > 0)
                        {
                            //fill in fields that may not be in entity
                            entity.RowId = efEntity.RowId;

                            MapToDB(entity, efEntity);

                            if (efEntity.EntityStateId == 0)
                            {
                                var url = string.Format(UtilityManager.GetAppKeyValue("credentialFinderSite") + "HoldersProfile/{0}", efEntity.Id);
                                //notify, and???
                                //EmailManager.NotifyAdmin( "Previously Deleted HoldersProfile has been reactivated", string.Format( "<a href='{2}'>HoldersProfile: {0} ({1})</a> was deleted and has now been reactivated.", efEntity.Name, efEntity.Id, url ) );
                                SiteActivity sa = new SiteActivity()
                                {
                                    ActivityType     = "HoldersProfile",
                                    Activity         = "Import",
                                    Event            = "Reactivate",
                                    Comment          = string.Format("HoldersProfile had been marked as deleted, and was reactivted by the import. CTID: {0}, SWP: {1}", entity.CTID, entity.Source),
                                    ActivityObjectId = entity.Id
                                };
                                new ActivityManager().SiteActivityAdd(sa);
                            }
                            //assume and validate, that if we get here we have a full record
                            if (efEntity.EntityStateId != 2)
                            {
                                efEntity.EntityStateId = 3;
                            }

                            //if ( IsValidDate( status.EnvelopeCreatedDate ) && status.LocalCreatedDate < efEntity.Created )
                            //{
                            //	efEntity.Created = status.LocalCreatedDate;
                            //}
                            if (IsValidDate(status.EnvelopeUpdatedDate) && status.LocalUpdatedDate != efEntity.LastUpdated)
                            {
                                efEntity.LastUpdated = status.LocalUpdatedDate;
                            }
                            //has changed?
                            if (HasStateChanged(context))
                            {
                                if (IsValidDate(status.EnvelopeUpdatedDate))
                                {
                                    efEntity.LastUpdated = status.LocalUpdatedDate;
                                }
                                else
                                {
                                    efEntity.LastUpdated = DateTime.Now;
                                }
                                //NOTE efEntity.EntityStateId is set to 0 in delete method )
                                count = context.SaveChanges();
                                //can be zero if no data changed
                                if (count >= 0)
                                {
                                    isValid = true;
                                }
                                else
                                {
                                    //?no info on error

                                    isValid = false;
                                    string message = string.Format(thisClassName + ".Save Failed", "Attempted to update a HoldersProfile. The process appeared to not work, but was not an exception, so we have no message, or no clue. HoldersProfile: {0}, Id: {1}", entity.Name, entity.Id);
                                    status.AddError("Error - the update was not successful. " + message);
                                    EmailManager.NotifyAdmin(thisClassName + ".Save Failed Failed", message);
                                }
                            }
                            else
                            {
                                //update entity.LastUpdated - assuming there has to have been some change in related data
                                //new EntityManager().UpdateModifiedDate( entity.RowId, ref status );
                            }
                            if (isValid)
                            {
                                if (!UpdateParts(entity, ref status))
                                {
                                    isValid = false;
                                }

                                SiteActivity sa = new SiteActivity()
                                {
                                    ActivityType     = "HoldersProfile",
                                    Activity         = "Import",
                                    Event            = "Update",
                                    Comment          = string.Format("HoldersProfile was updated by the import. CTID: {0}, Source: {1}", entity.CTID, entity.Source),
                                    ActivityObjectId = entity.Id
                                };
                                new ActivityManager().SiteActivityAdd(sa);

                                //if ( isValid || partsUpdateIsValid )
                                new EntityManager().UpdateModifiedDate(entity.RowId, ref status, efEntity.LastUpdated);
                            }
                        }
                        else
                        {
                            status.AddError("Error - update failed, as record was not found.");
                        }
                    }
                    else
                    {
                        //add
                        int newId = Add(entity, parentEntity, ref status);
                        if (newId == 0 || status.HasErrors)
                        {
                            isValid = false;
                        }
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
            {
                string message = HandleDBValidationError(dbex, thisClassName + string.Format(".Save. id: {0}, Name: {1}", entity.Id, entity.Name), "HoldersProfile");
                status.AddError(thisClassName + ".Save(). Error - the save was not successful. " + message);
            }
            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".Save. id: {0}, Name: {1}", entity.Id, entity.Name));
                status.AddError(thisClassName + ".Save(). Error - the save was not successful. " + message);
                isValid = false;
            }


            return(isValid);
        }
Exemplo n.º 19
0
        public int AddPendingRecord(Guid entityUid, string ctid, string registryAtId, ref string status)
        {
            DBEntity efEntity = new DBEntity();

            try
            {
                using (var context = new EntityContext())
                {
                    if (!IsValidGuid(entityUid))
                    {
                        status = thisClassName + " - A valid GUID must be provided to create a pending entity";
                        return(0);
                    }
                    //quick check to ensure not existing
                    ThisEntity entity = GetByCtid(ctid);
                    if (entity != null && entity.Id > 0)
                    {
                        return(entity.Id);
                    }

                    //only add DB required properties
                    //NOTE - an entity will be created via trigger
                    efEntity.Name          = "Placeholder until full document is downloaded";
                    efEntity.Description   = "Placeholder until full document is downloaded";
                    efEntity.EntityStateId = 1;
                    efEntity.RowId         = entityUid;
                    //watch that Ctid can be  updated if not provided now!!
                    efEntity.CTID           = ctid;
                    efEntity.SubjectWebpage = registryAtId;

                    efEntity.Created     = System.DateTime.Now;
                    efEntity.LastUpdated = System.DateTime.Now;

                    context.OccupationProfile.Add(efEntity);
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        SiteActivity sa = new SiteActivity()
                        {
                            ActivityType     = "OccupationProfile",
                            Activity         = "Import",
                            Event            = "Add Pending Occupation",
                            Comment          = string.Format("Pending Occupation was added by the import. ctid: {0}, registryAtId: {1}", ctid, registryAtId),
                            ActivityObjectId = efEntity.Id
                        };
                        new ActivityManager().SiteActivityAdd(sa);
                        return(efEntity.Id);
                    }

                    status = thisClassName + ".AddPendingRecord. Error - the save was not successful, but no message provided. ";
                }
            }

            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".AddPendingRecord. entityUid:  {0}, ctid: {1}", entityUid, ctid));
                status = thisClassName + ".AddPendingRecord. Error - the save was not successful. " + message;
            }
            return(0);
        }
Exemplo n.º 20
0
        /// <summary>
        /// 更新活动信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateActivity(SiteActivity model)
        {
            string safesql = "";

            safesql = "update ACT_SiteActivity set ";
            if (model.ActTitle != null && model.ActTitle != "")
            {
                safesql += "acttitle='" + model.ActTitle + "',";
            }
            if (model.Photo != null && model.Photo != "")
            {
                safesql += "Photo='" + model.Photo + "',";
            }
            if (model.SiteCode != null && model.SiteCode != "")
            {
                safesql += "SiteCode='" + model.SiteCode + "',";
            }
            if (model.ActContent != null && model.ActContent != "")
            {
                safesql += "ActContent='" + model.ActContent + "',";
            }
            if (model.StartTime != null)
            {
                safesql += "StartTime='" + model.StartTime + "',";
            }
            if (model.EndTime != null)
            {
                safesql += "EndTime='" + model.EndTime + "',";
            }
            if (model.CutOffTime != null)
            {
                safesql += "CutOffTime='" + model.CutOffTime + "',";
            }
            if (model.DisCount != null && model.DisCount != "")
            {
                safesql += "Discount='" + model.DisCount + "',";
            }
            if (model.OpenTime != null && model.OpenTime != "")
            {
                safesql += "OpenTime='" + model.OpenTime + "',";
            }
            if (model.CloseTime != null && model.CloseTime != "")
            {
                safesql += "CloseTime='" + model.CloseTime + "',";
            }
            if (model.DayLimit.ToString() != null && model.DayLimit.ToString() != "")
            {
                safesql += "DayLimit=" + model.DayLimit + ",";
            }
            if (model.Remark != null && model.Remark != "")
            {
                safesql += "Remark='" + model.Remark + "',";
            }
            safesql += "AddTime='" + DateTime.Now + "' where id='" + model.ID + "'";
            int rowsAffected = DbHelperSQL.ExecuteSql(safesql.ToString());

            if (rowsAffected > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// 删除活动
 /// </summary>
 public void DeleteSiteActivity(SiteActivity entity)
 {
     this.Delete <SiteActivity>(entity);
 }
Exemplo n.º 22
0
 /// <summary>
 /// 更新活动
 /// </summary>
 public void UpdateSiteActivity(SiteActivity entity)
 {
     Update <SiteActivity>(entity);
 }
Exemplo n.º 23
0
 /// <summary>
 /// 添加活动
 /// </summary>
 public void AddSiteActivity(SiteActivity entity)
 {
     Add <SiteActivity>(entity);
 }
Exemplo n.º 24
0
        /// <summary>
        /// add a PathwaySet
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity, ref SaveStatus status)
        {
            bool isValid  = true;
            var  efEntity = new DBEntity();

            using (var context = new EntityContext())
            {
                try
                {
                    //messages = new List<string>();
                    if (ValidateProfile(entity, ref status) == false)
                    {
                        return(false);
                    }


                    if (entity.Id == 0)
                    {
                        //entity.StatusId = 1;
                        MapToDB(entity, efEntity);

                        if (entity.RowId == null || entity.RowId == Guid.Empty)
                        {
                            efEntity.RowId = entity.RowId = Guid.NewGuid();
                        }
                        else
                        {
                            efEntity.RowId = entity.RowId;
                        }

                        if (IsValidDate(status.EnvelopeCreatedDate))
                        {
                            efEntity.Created     = status.LocalCreatedDate;
                            efEntity.LastUpdated = status.LocalCreatedDate;
                        }
                        else
                        {
                            efEntity.Created     = System.DateTime.Now;
                            efEntity.LastUpdated = System.DateTime.Now;
                        }

                        context.PathwaySet.Add(efEntity);

                        // submit the change to database
                        int count = context.SaveChanges();
                        if (count > 0)
                        {
                            entity.Id = efEntity.Id;
                            //add log entry
                            SiteActivity sa = new SiteActivity()
                            {
                                ActivityType     = "PathwaySet",
                                Activity         = "Import",
                                Event            = "Add",
                                Comment          = string.Format("Full PathwaySet was added by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                                ActivityObjectId = entity.Id
                            };
                            new ActivityManager().SiteActivityAdd(sa);
                            UpdateParts(entity, ref status);

                            return(true);
                        }
                        else
                        {
                            //?no info on error
                            status.AddError("Error - the profile was not saved. ");
                            string message = string.Format("PathwayManager.Add Failed. Attempted to add a PathwaySet. The process appeared to not work, but was not an exception, so we have no message, or no clue.PathwaySet. PathwaySet: {0}, createdById: {1}", entity.Name, entity.CreatedById);
                            EmailManager.NotifyAdmin(thisClassName + ".Add Failed", message);
                        }
                    }
                    else
                    {
                        efEntity = context.PathwaySet
                                   .SingleOrDefault(s => s.Id == entity.Id);

                        if (efEntity != null && efEntity.Id > 0)
                        {
                            //for updates, chances are some fields will not be in interface, don't map these (ie created stuff)
                            MapToDB(entity, efEntity);
                            if (IsValidDate(status.EnvelopeCreatedDate) && status.LocalCreatedDate < efEntity.Created)
                            {
                                efEntity.Created = status.LocalCreatedDate;
                            }
                            if (IsValidDate(status.EnvelopeUpdatedDate) && status.LocalUpdatedDate != efEntity.LastUpdated)
                            {
                                efEntity.LastUpdated = status.LocalUpdatedDate;
                            }
                            //has changed?
                            if (HasStateChanged(context))
                            {
                                if (IsValidDate(status.EnvelopeUpdatedDate))
                                {
                                    efEntity.LastUpdated = status.LocalUpdatedDate;
                                }
                                else
                                {
                                    efEntity.LastUpdated = DateTime.Now;
                                }
                                int count = context.SaveChanges();
                                //can be zero if no data changed
                                if (count >= 0)
                                {
                                    isValid = true;
                                }
                                else
                                {
                                    //?no info on error
                                    status.AddError("Error - the update was not successful. ");
                                    string message = string.Format(thisClassName + ".Save Failed", "Attempted to update a PathwaySet. The process appeared to not work, but was not an exception, so we have no message, or no clue. PathwayId: {0}, Id: {1}, updatedById: {2}", entity.Id, entity.Id, entity.LastUpdatedById);
                                    EmailManager.NotifyAdmin(thisClassName + ". Pathway_Update Failed", message);
                                }
                            }
                            //continue with parts regardless
                            UpdateParts(entity, ref status);
                        }
                        else
                        {
                            status.AddError("Error - update failed, as record was not found.");
                        }
                    }
                }
                //catch ( System.Data.Entity.Validation.DBEntityValidationException dbex )
                //{
                //	//LoggingHelper.LogError( dbex, thisClassName + string.Format( ".ContentAdd() DBEntityValidationException, Type:{0}", entity.TypeId ) );
                //	string message = thisClassName + string.Format( ".Pathway_Add() DBEntityValidationException, PathwayId: {0}", PathwaySet.Id );
                //	foreach ( var eve in dbex.EntityValidationErrors )
                //	{
                //		message += string.Format( "\rEntity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                //			eve.Entry.Entity.GetType().Name, eve.Entry.State );
                //		foreach ( var ve in eve.ValidationErrors )
                //		{
                //			message += string.Format( "- Property: \"{0}\", Error: \"{1}\"",
                //				ve.PropertyName, ve.ErrorMessage );
                //		}

                //		LoggingHelper.LogError( message, true );
                //	}
                //}
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Save(), PathwaySet: '{0}'", entity.Name));
                    status.AddError(string.Format("PathwayManager.Save Failed. PathwaySet: {0}, createdById: {1}, Error: {2}", entity.Name, entity.CreatedById, ex.Message));
                    isValid = false;
                }
            }

            return(isValid);
        }
Exemplo n.º 25
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtName.Text.Trim() != null && txtName.Text.Trim() != "")
            {
                //上传图标
                string strIconFileName     = string.Empty; //图标路径
                string strIconSaveFileName = string.Empty; //网址路径
                try
                {
                    if (this.file0.PostedFile.FileName == "")
                    {
                        strIconSaveFileName = "";
                    }
                    else
                    {
                        if (!System.IO.Directory.Exists(Server.MapPath("~") + @"/Images"))
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath("~") + @"/Images");
                        }
                        if (!System.IO.Directory.Exists(String.Format(@"{0}/Images/{1}", Server.MapPath("~"), Session["strSiteCode"].ToString())))
                        {
                            System.IO.Directory.CreateDirectory(String.Format(@"{0}/Images/{1}", Server.MapPath("~"), Session["strSiteCode"].ToString()));
                        }
                        string orignalName = this.file0.PostedFile.FileName;                      //获取客户机上传文件的文件名
                        string extendName  = orignalName.Substring(orignalName.LastIndexOf(".")); //获取扩展名

                        if (extendName != ".gif" && extendName != ".jpg" && extendName != ".jpeg" && extendName != ".png")
                        {
                            MessageBox.Show(this, "文件格式有误!");
                            return;
                        }//检查文件格式
                        string newName = String.Format("{0}_{1}{2}", DateTime.Now.Millisecond, file0.PostedFile.ContentLength, extendName);//对文件进行重命名
                        strIconFileName     = String.Format(@"{0}Images/{1}/{2}", Server.MapPath("~"), Session["strSiteCode"].ToString(), newName);
                        strIconSaveFileName = String.Format(@"Images/{0}/{1}", Session["strSiteCode"].ToString(), newName);
                        file0.PostedFile.SaveAs(strIconFileName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "上传发生错误!原因是:" + ex.ToString());
                }

                SiteActivity model = new SiteActivity();
                model.ID         = Guid.NewGuid().ToString("N").ToUpper();
                model.ActTitle   = txtName.Text.Trim();
                model.SiteCode   = GlobalSession.strSiteCode;
                model.ActContent = hd_content.Value;
                model.StartTime  = starttime.Text;
                model.EndTime    = endtime.Text;
                model.Remark     = txtSummary.Text;
                model.CutOffTime = cutTime.Text;
                model.DisCount   = Discount.Text;
                model.Photo      = strIconSaveFileName;
                model.OpenTime   = opentime.Text;
                model.CloseTime  = closetime.Text;
                if (daylimit.Text.Trim() != null && daylimit.Text.Trim() != "" && Convert.ToInt32(daylimit.Text) > -1)
                {
                    model.DayLimit = Convert.ToInt32(daylimit.Text);
                }
                model.ActStatus = ActStatusyes.Checked?1:0;//默认1 生效
                SiteActivityDAL dal = new SiteActivityDAL();
                if (dal.SaveActivity(model) > 0)
                {
                    MessageBox.Show(this, "添加成功!");
                }
                else
                {
                    MessageBox.Show(this, "添加失败!");
                }
            }
            else
            {
                MessageBox.Show(this, "请输入相关名称!");
            }
        }
        } //

        public static List <SiteActivity> SearchAll(BaseSearchModel parms)
        {
            string              connectionString = DBConnectionRO();
            SiteActivity        entity           = new SiteActivity();
            List <SiteActivity> list             = new List <SiteActivity>();

            if (parms.PageSize == 0)
            {
                parms.PageSize = 25;
            }
            int skip = 0;

            if (parms.PageNumber > 1)
            {
                skip = (parms.PageNumber - 1) * parms.PageSize;
            }
            if (string.IsNullOrWhiteSpace(parms.OrderBy))
            {
                parms.OrderBy      = "CreatedDate";
                parms.IsDescending = true;
            }
            if (parms.StartDate == null || parms.StartDate < new DateTime(2015, 1, 1))
            {
                parms.StartDate = new DateTime(2015, 1, 1);
            }
            if (parms.EndDate == null || parms.EndDate < new DateTime(2015, 1, 1))
            {
                parms.EndDate = DateTime.Now;
            }

            using (var context = new ViewContext())
            {
                var query = from Results in context.Activity_Summary
                            .Where(s => s.Activity != "Session")
                            select Results;
                if (!string.IsNullOrWhiteSpace(parms.Keyword))
                {
                    query = from Results in query
                            .Where(s => (s.Activity.Contains(parms.Keyword) ||
                                         (s.Event.Contains(parms.Keyword)) ||
                                         (s.Comment.Contains(parms.Keyword))
                                         ))
                            select Results;
                }
                parms.TotalRows = query.Count();
                if (parms.IsDescending)
                {
                    if (parms.OrderBy == "CreatedDate")
                    {
                        query = query.OrderByDescending(p => p.CreatedDate);
                    }
                    else if (parms.OrderBy == "Activity")
                    {
                        query = query.OrderByDescending(p => p.Activity);
                    }
                    else if (parms.OrderBy == "Event")
                    {
                        query = query.OrderByDescending(p => p.Event);
                    }
                    else if (parms.OrderBy == "ActionByUser")
                    {
                        query = query.OrderByDescending(p => p.ActionByUser);
                    }
                    else
                    {
                        query = query.OrderByDescending(p => p.CreatedDate);
                    }
                }
                else
                {
                    if (parms.OrderBy == "CreatedDate")
                    {
                        query = query.OrderBy(p => p.CreatedDate);
                    }
                    else if (parms.OrderBy == "Activity")
                    {
                        query = query.OrderBy(p => p.Activity);
                    }
                    else if (parms.OrderBy == "Event")
                    {
                        query = query.OrderBy(p => p.Event);
                    }
                    else if (parms.OrderBy == "ActionByUser")
                    {
                        query = query.OrderBy(p => p.ActionByUser);
                    }

                    else
                    {
                        query = query.OrderBy(p => p.CreatedDate);
                    }
                }

                var results = query.Skip(skip).Take(parms.PageSize)
                              .ToList();
                if (results != null && results.Count > 0)
                {
                    foreach (Views.Activity_Summary item in results)
                    {
                        entity              = new SiteActivity();
                        entity.Id           = item.Id;
                        entity.Activity     = item.Activity;
                        entity.Event        = item.Event;
                        entity.Comment      = item.Comment;
                        entity.Created      = ( DateTime )item.CreatedDate;
                        entity.ActionByUser = item.ActionByUser;
                        entity.Referrer     = entity.Referrer;
                        list.Add(entity);
                    }
                }
            }



            return(list);
        } //
        } //

        public static List <SiteActivity> Search(string pFilter, string pOrderBy, int pageNumber, int pageSize, ref int pTotalRows, int userId = 0)
        {
            string              connectionString = DBConnectionRO();
            SiteActivity        item             = new SiteActivity();
            List <SiteActivity> list             = new List <SiteActivity>();
            var result = new DataTable();

            using (SqlConnection c = new SqlConnection(connectionString))
            {
                c.Open();

                if (string.IsNullOrEmpty(pFilter))
                {
                    pFilter = "";
                }

                using (SqlCommand command = new SqlCommand("Activity_Search", c))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new SqlParameter("@Filter", pFilter));
                    command.Parameters.Add(new SqlParameter("@SortOrder", pOrderBy));
                    command.Parameters.Add(new SqlParameter("@StartPageIndex", pageNumber));
                    command.Parameters.Add(new SqlParameter("@PageSize", pageSize));

                    SqlParameter totalRows = new SqlParameter("@TotalRows", pTotalRows);
                    totalRows.Direction = ParameterDirection.Output;
                    command.Parameters.Add(totalRows);

                    using (SqlDataAdapter adapter = new SqlDataAdapter())
                    {
                        adapter.SelectCommand = command;
                        adapter.Fill(result);
                    }
                    string rows = command.Parameters[4].Value.ToString();
                    try
                    {
                        pTotalRows = Int32.Parse(rows);
                    }
                    catch (Exception ex)
                    {
                        pTotalRows = 0;
                        LoggingHelper.LogError(ex, thisClassName + string.Format(".Search() - Execute proc, Message: {0} \r\n Filter: {1} \r\n", ex.Message, pFilter));

                        item = new SiteActivity
                        {
                            ActivityType = "Unexpected error encountered. System administration has been notified. Please try again later. ",
                            Comment      = ex.Message,
                            Event        = "error"
                        };
                        list.Add(item);
                        return(list);
                    }
                }

                foreach (DataRow dr in result.Rows)
                {
                    item                  = new SiteActivity();
                    item.Id               = GetRowColumn(dr, "Id", 0);
                    item.CreatedDate      = GetRowColumn(dr, "CreatedDate", DateTime.Now);
                    item.ActivityType     = GetRowColumn(dr, "ActivityType", "ActivityType");
                    item.Activity         = GetRowColumn(dr, "Activity", "");
                    item.Event            = GetRowColumn(dr, "Event", "");
                    item.Comment          = GetRowColumn(dr, "Comment", "");
                    item.ActionByUser     = GetRowColumn(dr, "ActionByUser", "");
                    item.ActionByUserId   = GetRowColumn(dr, "ActionByUserId", 0);
                    item.Referrer         = GetRowColumn(dr, "Referrer", "");
                    item.ActivityObjectId = GetRowColumn(dr, "ActivityObjectId", 0);
                    item.IPAddress        = GetRowColumn(dr, "IPAddress", "");
                    item.SessionId        = GetRowColumn(dr, "SessionId", "");
                    item.IsBot            = GetRowColumn(dr, "IsBot", false);
                    //item.EntityTypeId = GetRowColumn( dr, "EntityTypeId", 0 );
                    //item.OwningOrgId = GetRowColumn( dr, "OwningOrgId", 0 );
                    item.Organization = GetRowColumn(dr, "Organization", "");
                    //N/A
                    //item.ParentObject = GetRowColumn( dr, "ParentObject", "" );
                    //item.ParentEntityTypeId = GetRowColumn( dr, "ParentEntityTypeId", 0 );
                    //item.ParentRecordId = GetRowColumn( dr, "ParentRecordId", 0 );

                    list.Add(item);
                }

                return(list);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// 处理回复消息
        /// "text":回复文本消息处理,MsgValue对应回复的文本
        /// "sub_auto_coupon":回复订阅自动优惠券处理,MsgValue对应回复的图文消息ID
        /// "auto_news_article":根据文章自动生成图文消息进行回复,MsgValue为类别ID
        /// "news":回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
        /// </summary>
        /// <param name="replyMsgType"></param>
        /// <param name="replyMsgValue"></param>
        /// <param name="customParams"></param>
        /// <returns></returns>
        private string ProcessReply(RequestMsgModel msgModel, string replyMsgType, string replyMsgValue)
        {
            string res = string.Empty;

            try
            {
                switch (replyMsgType.ToLower())
                {
                case "text":
                    //回复文本消息处理,MsgValue对应回复的文本
                    TextResponseMsgModel textMsg = new TextResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                    };
                    res = textMsg.ToString();
                    break;

                case "voice":
                    //回复语音消息处理,MsgValue对应回复的文本
                    VoiceResponseMsgModel voiceMsg = new VoiceResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                    };
                    Media media = MediaDAL.CreateInstance().GetMediaByID(replyMsgValue);
                    if (media != null && !string.IsNullOrEmpty(media.MediaID))
                    {
                        voiceMsg.MediaId = media.MediaID;
                    }
                    res = voiceMsg.ToString();
                    break;

                case "wxpay_test":
                    //用于微信支付测试
                    TextResponseMsgModel textMsgx = new TextResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        Content      = string.Format("<a href='{0}/Payment/wxpay/wxpayDemo.aspx?openid={1}'>微信支付测试</a>", GetSiteUrl(), msgModel.FromUserName)
                    };
                    res = textMsgx.ToString();
                    break;

                case "transfer_customer_service":
                    //将消息转发到多客服
                    TransferCustomerServiceResponseMsgModel transferMsg = new TransferCustomerServiceResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                    };
                    res = transferMsg.ToString();
                    break;

                case "sub_auto_coupon":
                    //回复订阅自动优惠券处理,MsgValue对应回复的优惠券图文消息ID
                    //SubscribeCouponActHandle sch = new SubscribeCouponActHandle();
                    SiteActivityDAL dal      = new SiteActivityDAL();
                    SiteActivity    activity = dal.GetSiteAct(siteCode, "Coupon");
                    if (activity != null)
                    {
                        CouponDAL cdal = new CouponDAL();
                        if (!cdal.ExistCoupon(siteCode, activity.ID, msgModel.FromUserName))
                        {
                            Coupon coupon = new Coupon()
                            {
                                SiteCode       = siteCode,
                                SiteActivityID = activity.ID,
                                OpenID         = msgModel.FromUserName,
                                //CouponCode = msgModel.FromUserName,
                                CouponStatus = 0
                            };
                            cdal.InsertInfo(coupon);
                        }
                    }
                    CouponNewsDAL nmDAL = new CouponNewsDAL();
                    CouponNews    nm    = nmDAL.GetCouponNews(replyMsgValue);
                    if (nm != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        articles.Add(new Article()
                        {
                            Title       = nm.Title,
                            Description = nm.Description,
                            PicUrl      = GetPicUrl(nm.PicUrl),
                            Url         = TransformUrl(nm.Url, msgModel)
                        });
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_coupon_category":
                    SiteActivityDAL dalCatList  = new SiteActivityDAL();
                    SiteActivity    activityCat = dalCatList.GetSiteAct(siteCode, "Coupon");
                    if (activityCat != null)
                    {
                        CouponDAL cdal = new CouponDAL();
                        if (!cdal.ExistCoupon(siteCode, activityCat.ID, msgModel.FromUserName))
                        {
                            Coupon coupon = new Coupon()
                            {
                                SiteCode       = siteCode,
                                SiteActivityID = activityCat.ID,
                                OpenID         = msgModel.FromUserName,
                                //CouponCode = msgModel.FromUserName,
                                CouponStatus = 0
                            };
                            cdal.InsertInfo(coupon);
                        }
                    }
                    ArticleDAL catDal = new ArticleDAL();
                    DataSet    cdsCat = catDal.GetCategoryList(siteCode, replyMsgValue);
                    if (cdsCat != null && cdsCat.Tables.Count > 0 && cdsCat.Tables[0] != null && cdsCat.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in cdsCat.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 30),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_news_article":
                    //根据文章自动生成图文消息进行回复,MsgValue为文章ID
                    ArticleDAL aDal = new ArticleDAL();
                    DataSet    ds   = aDal.GetArticleDetail(replyMsgValue);
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 100),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_news_category":
                    //根据类别自动生成图文消息进行回复,MsgValue为类别ID
                    ArticleDAL cDal = new ArticleDAL();
                    DataSet    cds  = cDal.GetCategoryList(siteCode, replyMsgValue);
                    if (cds != null && cds.Tables.Count > 0 && cds.Tables[0] != null && cds.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in cds.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 30),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "coupon":
                    //回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
                    NewsMsgDAL nmDAL1 = new NewsMsgDAL();
                    NewsMsg    nms    = nmDAL1.GetNewsMsg(replyMsgValue);
                    if (nms != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        articles.Add(new Article()
                        {
                            Title       = nms.Title,
                            Description = nms.Description,
                            PicUrl      = GetPicUrl(nms.PicUrl),
                            Url         = TransformUrl(nms.Url, msgModel)
                        });
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "news":
                    //回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
                    NewsMsgDAL      nmDALs   = new NewsMsgDAL();
                    IList <NewsMsg> newsMsgs = nmDALs.GetNewsMsgs(replyMsgValue);
                    if (newsMsgs != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (NewsMsg msg in newsMsgs)
                        {
                            articles.Add(new Article()
                            {
                                Title       = msg.Title,
                                Description = msg.Description,
                                PicUrl      = GetPicUrl(msg.PicUrl),
                                Url         = TransformUrl(msg.Url, msgModel)
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "url":
                    //根据文章自动生成图文消息进行回复,MsgValue为文章ID
                    DAL.SYS.AccountDAL dalUrl = new DAL.SYS.AccountDAL();
                    DataSet            dsUrl  = dalUrl.GetAccountExtData(replyMsgValue);
                    if (dsUrl != null && dsUrl.Tables.Count > 0 && dsUrl.Tables[0] != null && dsUrl.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in dsUrl.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Name"].ToString(),
                                Description = dr["Summary"].ToString(),
                                PicUrl      = GetPicUrl(dr["Photo"].ToString()),
                                Url         = GetSiteInfo(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "hp_photo_text":
                    //为当前hp_photo对应的照片附加文字信息
                    PhotoDAL photoDal = new PhotoDAL();
                    if (photoDal.ExistPhoto(siteCode, msgModel.FromUserName, 0))
                    {
                        TextRequestMsgModel temp = msgModel as TextRequestMsgModel;
                        string text = temp.Content.Replace("#ms", "");
                        //附加图片文字
                        photoDal.UpdateAttachText(siteCode, msgModel.FromUserName, text);
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                        };
                        res = textMsg2.ToString();
                    }
                    else
                    {
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = "对不起,您暂未参加图片打印活动!"
                        };
                        res = textMsg2.ToString();
                    }
                    break;

                case "hp_photo_ticket":
                    //对当前hp_photo对应的照片进行打印认证
                    PrintCodeDAL        printCodeDAL = new PrintCodeDAL();
                    TextRequestMsgModel temp1        = msgModel as TextRequestMsgModel;
                    string printCode = temp1.Content.Replace("#dy", "");
                    string clientID  = printCodeDAL.GetClientIDByPrintCode(printCode, siteCode);
                    ExceptionLogDAL.InsertExceptionLog(new ExceptionLog()
                    {
                        Message = clientID
                    });
                    if (!string.IsNullOrEmpty(clientID))
                    {
                        PhotoDAL photoDal1 = new PhotoDAL();
                        photoDal1.UpdatePrintInfo(printCode, clientID, siteCode, msgModel.FromUserName);
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                        };
                        res = textMsg2.ToString();
                        //TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        //{
                        //    ToUserName = msgModel.FromUserName,
                        //    FromUserName = msgModel.ToUserName,
                        //    CreateTime = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        //    Content = "照片打印中,请稍侯..."
                        //};
                        //res = textMsg2.ToString();
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                ExceptionLogDAL.InsertExceptionLog(ex);
            }
            return(res);
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            //NOTE: consider the IOER approach that all candidate records are first downloaded, and then a separate process does the import


            LoggingHelper.DoTrace(1, "======================= STARTING IMPORT =======================");
            TimeZone zone = TimeZone.CurrentTimeZone;
            // Demonstrate ToLocalTime and ToUniversalTime.
            DateTime local     = zone.ToLocalTime(DateTime.Now);
            DateTime universal = zone.ToUniversalTime(DateTime.Now);

            LoggingHelper.DoTrace(1, "Local time: " + local);
            LoggingHelper.DoTrace(1, "Universal time: " + universal);

            //need to determine how to get last start date
            //may be run multiple times during day, so use a schedule type
            string scheduleType      = UtilityManager.GetAppKeyValue("scheduleType", "daily");
            int    deleteAction      = UtilityManager.GetAppKeyValue("deleteAction", 0);
            bool   doingDownloadOnly = UtilityManager.GetAppKeyValue("DoingDownloadOnly", false);

            string defaultCommunity    = UtilityManager.GetAppKeyValue("defaultCommunity");
            string additionalCommunity = UtilityManager.GetAppKeyValue("additionalCommunity");

            #region  Import Type/Arguments
            if (args != null)
            {
                if (args.Length >= 1)
                {
                    scheduleType = args[0];
                }

                if (args.Length == 2)
                {
                    //
                    var altCommunity = args[1];
                    if (!string.IsNullOrWhiteSpace(altCommunity) && altCommunity.ToLower() == additionalCommunity.ToLower())
                    {
                        //has to match additional to be valid
                        defaultCommunity = additionalCommunity;
                    }
                }
            }


            RegistryImport registryImport = new RegistryImport(defaultCommunity);

            string startingDate = DateTime.Now.AddDays(-1).ToString();
            //typically will want this as registry server is UTC (+6 hours from central)
            bool usingUTC_ForTime = UtilityManager.GetAppKeyValue("usingUTC_ForTime", true);


            string endingDate    = "";
            string importResults = "";

            //could ignore end date until a special scedule type of adhoc is used, then read the dates from config
            importResults = DisplayMessages(string.Format(" - Schedule type: {0} ", scheduleType));
            int minutes = 0;

            if (Int32.TryParse(scheduleType, out minutes))
            {
                //minutes
                //may want more flexibility and use input parms
                if (minutes < 1 || minutes > 1440)                 //doesn't really matter
                {
                    DisplayMessages(string.Format("invalid value encountered for Minutes option: {0} - defaulting to 60.", scheduleType));
                    minutes = 60;
                }
                if (usingUTC_ForTime)
                {
                    //UTC is +6 hours (360 minutes), so subtract entered minutes and add to current time
                    // ex: If -60, want 5 hours (360 - 60)
                    minutes = minutes * -1;
                    //startingDate = DateTime.Now.AddMinutes( minutes ).ToString( "yyyy-MM-ddTHH:mm:ss" );
                    startingDate = zone.ToUniversalTime(DateTime.Now.AddMinutes(minutes)).ToString("yyyy-MM-ddTHH:mm:ss");
                    //no end date?
                    endingDate = "";
                }
                else
                {
                    startingDate = DateTime.Now.AddMinutes(-minutes).ToString("yyyy-MM-ddTHH:mm:ss");
                    //the server date is UTC, so if we leave enddate open, we will get the same stuff all day, so setting an endate to the current hour
                    endingDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
                }
                importResults = importResults + "<br/>" + DisplayMessages(string.Format(" - Community: {0}, Updates since: {1} {2}", defaultCommunity, startingDate, usingUTC_ForTime ? " (UTC)" : ""));
            }
            else if (scheduleType == "sinceLastRun")
            {
                SiteActivity lastRun = ActivityServices.GetLastImport();
                if (usingUTC_ForTime)
                {
                    startingDate = zone.ToUniversalTime(lastRun.Created).ToString("yyyy-MM-ddTHH:mm:ss");
                }
                else
                {
                    startingDate = lastRun.Created.ToString("yyyy-MM-ddTHH:mm:ss");
                }
                endingDate    = "";
                importResults = importResults + "<br/>" + DisplayMessages(string.Format(" - Updates since: {0} {1}", startingDate, usingUTC_ForTime ? " (UTC)" : ""));
            }
            else if (scheduleType == "adhoc")
            {
                startingDate = UtilityManager.GetAppKeyValue("startingDate", "");
                endingDate   = UtilityManager.GetAppKeyValue("endingDate", "");
                DateTime dtcheck = System.DateTime.Now;                                         //LoggingHelper.DoTrace( 1, string.Format( " - Updates from: {0} to {1} ", startingDate, endingDate ) );

                if (usingUTC_ForTime)
                {
                    if (DateTime.TryParse(startingDate, out dtcheck))
                    {
                        startingDate = zone.ToUniversalTime(dtcheck).ToString("yyyy-MM-ddTHH:mm:ss");
                    }
                    if (DateTime.TryParse(endingDate, out dtcheck))
                    {
                        endingDate = zone.ToUniversalTime(dtcheck).ToString("yyyy-MM-ddTHH:mm:ss");
                    }
                    //no end date?
                    //endingDate = "";
                }
                importResults = importResults + "<br/>" + DisplayMessages(string.Format(" - Updates from: {0} to {1} for community: {2}", startingDate, endingDate, defaultCommunity));
            }
            else if (scheduleType == "hourly")
            {
                if (usingUTC_ForTime)
                {
                    //6 hour diff, so add 5 hours, equiv to +6 hours - 1 hour
                    startingDate = zone.ToUniversalTime(DateTime.Now.AddHours(-1)).ToString("yyyy-MM-ddTHH:mm:ss");
                }
                else
                {
                    startingDate = DateTime.Now.AddHours(-1).ToString("yyyy-MM-ddTHH:mm:ss");
                    //format into: 2016-08-01T23:59:59
                    //the server date is UTC, so if we leave enddate open, we will get the same stuff all day, so setting an endate to the current hour
                    //HOWEVER - THIS COULD RESULT IN BEING 6 HOURS BEHIND
                    endingDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
                }
                //LoggingHelper.DoTrace( 1, string.Format( " - Updates since: {0} ", startingDate ) );
                importResults = importResults + "<br/>" + DisplayMessages(string.Format(" - Updates since: {0} {1}, community: {2}", startingDate, usingUTC_ForTime ? " (UTC)" : "", defaultCommunity));
            }
            else
            {
                //assume daily
                startingDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-ddTHH:mm:ss");
                //format into: 2016-08-01T23:59:59
                endingDate = "";
                //LoggingHelper.DoTrace( 1, string.Format( " - Updates since: {0} ", startingDate ) );
                importResults = importResults + "<br/>" + DisplayMessages(string.Format(" - Updates since: {0} ", startingDate));
            }
            #endregion
            //===================================================================================================
            if (!doingDownloadOnly)
            {
                LogStart();
            }
            //set to zero to handle all, or a number to limit records to process
            //partly for testing
            //although once can sort by date, we can use this, and update the start date
            int maxImportRecords = UtilityManager.GetAppKeyValue("maxImportRecords", 50);

            //NOTE - NEED TO REBUILD CACHE TABLES BEFORE BUILDING ELASTIC INDICES

            //Actions: 0-normal; 1-DeleteOnly; 2-SkipDelete
            int recordsDeleted = 0;
            if (deleteAction < 2)
            {
                //handle deleted records
                importResults = importResults + "<br/>" + HandleDeletes(defaultCommunity, startingDate, endingDate, maxImportRecords, ref recordsDeleted);
            }
            int recordsImported = 0;
            if (deleteAction != 1)
            {
                //do manifests
                if (UtilityManager.GetAppKeyValue("importing_condition_manifest_schema", true))
                {
                    importResults = importResults + "<br/>" + registryImport.Import("condition_manifest_schema", CodesManager.ENTITY_TYPE_CONDITION_MANIFEST, startingDate, endingDate, maxImportRecords, doingDownloadOnly, ref recordsImported);
                }
                //
                if (UtilityManager.GetAppKeyValue("importing_cost_manifest_schema", true))
                {
                    importResults = importResults + "<br/>" + registryImport.Import("cost_manifest_schema", CodesManager.ENTITY_TYPE_COST_MANIFEST, startingDate, endingDate, maxImportRecords, doingDownloadOnly, ref recordsImported);
                }

                //handle credentials
                //
                if (UtilityManager.GetAppKeyValue("importing_credential", true))
                {
                    importResults = importResults + "<br/>" + registryImport.Import("credential", CodesManager.ENTITY_TYPE_CREDENTIAL, startingDate, endingDate, maxImportRecords, doingDownloadOnly, ref recordsImported);
                }
                //handle assessments
                //
                if (UtilityManager.GetAppKeyValue("importing_assessment_profile", true))
                {
                    importResults = importResults + "<br/>" + registryImport.Import("assessment_profile", CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, startingDate, endingDate, maxImportRecords, doingDownloadOnly, ref recordsImported);
                }

                //handle learning opps
                //
                if (UtilityManager.GetAppKeyValue("importing_learning_opportunity_profile", true))
                {
                    importResults = importResults + "<br/>" + registryImport.Import("learning_opportunity_profile", CodesManager.ENTITY_TYPE_LEARNING_OPP_PROFILE, startingDate, endingDate, maxImportRecords, doingDownloadOnly, ref recordsImported);
                }
                //
                if (UtilityManager.GetAppKeyValue("importing_competency_frameworks", true))
                {
                    importResults = importResults + "<br/>" + new CompetencyFramesworksImport().Import(startingDate, endingDate, maxImportRecords, defaultCommunity, doingDownloadOnly);
                }

                //new pathways
                //if ( UtilityManager.GetAppKeyValue( "importing_pathways", true ) )
                //	importResults = importResults + "<br/>" + new CompetencyFramesworksImport().Import( startingDate, endingDate, maxImportRecords, doingDownloadOnly );

                //handle organizations
                //might be better to do last, then can populate placeholders, try first
                //
                if (UtilityManager.GetAppKeyValue("importing_organization", true))
                {
                    importResults = importResults + "<br/>" + registryImport.Import("organization", 2, startingDate, endingDate, maxImportRecords, doingDownloadOnly, ref recordsImported);
                }

                if (!doingDownloadOnly && recordsImported > 0)
                {
                    if (UtilityManager.GetAppKeyValue("processingPendingRecords", true))
                    {
                        //==============================================================
                        //import pending
                        string pendingStatus = new RegistryServices().ImportPending();

                        importResults = importResults + "<br/>TODO: add stats from ImportPending.";
                    }
                }
            }

            //===================================================================================================
            if (!doingDownloadOnly)
            {
                if (recordsImported > 0 || recordsDeleted > 0)
                {
                    //update elastic if not included - probably will always delay elastic, due to multiple possible updates
                    //may want to move this to services for use by other process, including adhoc imports
                    if (UtilityManager.GetAppKeyValue("delayingAllCacheUpdates", true))
                    {
                        //update elastic if a elasticSearchUrl exists
                        if (UtilityManager.GetAppKeyValue("elasticSearchUrl") != "")
                        {
                            LoggingHelper.DoTrace(1, string.Format("===  *****************  UpdateElastic  ***************** "));
                            ElasticServices.UpdateElastic(true);
                        }
                    }

                    if (recordsImported > 0)
                    {
                        //set all resolved records in Import_EntityResolution to be resolved.
                        LoggingHelper.DoTrace(1, string.Format("===  *****************  SetAllResolvedEntities  ***************** "));
                        new ImportManager().SetAllResolvedEntities();
                    }

                    //update code table counts
                    LoggingHelper.DoTrace(1, string.Format("===  *****************  UpdateCodeTableCounts  ***************** "));
                    new CacheManager().UpdateCodeTableCounts();

                    //send summary email
                    string message = string.Format("<h2>Import Results</h2><p>{0}</p>", importResults);
                    EmailManager.NotifyAdmin(string.Format("Credential Finder Import Results ({0})", envType), message);
                    new ActivityServices().AddActivity(new SiteActivity()
                    {
                        ActivityType = "System", Activity = "Import", Event = "End", Comment = string.Format("Summary: {0} records were imported, {1} records were deleted.", recordsImported, recordsDeleted), SessionId = "batch job", IPAddress = "local"
                    });
                }
                else
                {
                    new ActivityServices().AddActivity(new SiteActivity()
                    {
                        ActivityType = "System", Activity = "Import", Event = "End", Comment = "No data was found to import", SessionId = "batch job", IPAddress = "local"
                    });
                }
            }

            //summary, and logging
            LoggingHelper.DoTrace(1, "======================= all done ==============================");
        }