Exemplo n.º 1
0
        /// <summary>
        /// 作者:Vincen
        /// 时间:2014.05.27
        /// 描述:新增操作日志信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool CreateExceptionLogs(ExceptionLogs model)
        {
            using (var ldb = new EmeLogsEntities())
            {
                var elog = new ExceptionLogs()
                {
                    ExceptionType = model.ExceptionType,
                    Message = model.Message,
                    IsTreat = false,
                    UserHostAddress = WebHelper.GetCurrentIpAddress(),
                    CreateBy = model.CreateBy,
                    CreateTime = model.CreateTime,
                    Remark = model.Remark
                };

                ldb.Entry(elog).State = EntityState.Added;
                return ldb.SaveChanges() > 0;
            }
        }
Exemplo n.º 2
0
        public AutocompleteItem[] SearchWikis(string searchTerm)
        {
            try
            {
                List <AutocompleteItem> items    = new List <AutocompleteItem>();
                WikiArticles            articles = WikiArticles.GetWikiArticlesBySearchTerm(TSAuthentication.GetLoginUser(), searchTerm);

                foreach (WikiArticle article in articles)
                {
                    items.Add(new AutocompleteItem(article.ArticleName, article.ArticleID.ToString(), article.ArticleID));
                }

                return(items.ToArray());
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), ex, "WikiService.SearchWikis");
            }
            return(null);
        }
Exemplo n.º 3
0
        public static string GetItems(RestCommand command, bool orderByDateCreated = false, int?limitNumber = null, bool isCustomer = false)
        {
            ContactsView items     = new ContactsView(command.LoginUser);
            string       xmlString = string.Empty;

            try
            {
                if (orderByDateCreated)
                {
                    //This seems to be Zapier only
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID, command.Filters, null, null, "DateCreated DESC", limitNumber, isCustomer);
                }
                else
                {
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID, command.Filters, command.PageNumber, command.PageSize, isCustomer: isCustomer);
                }

                //SQL filtering was done already, there's no need for .NET filtering thus the empty collection for the last parameter
                xmlString = items.GetXml("Contacts", "Contact", true, new System.Collections.Specialized.NameValueCollection(), command.IsPaging);
            }
            catch (Exception ex)
            {
                //if something fails use the old method. This one does not have paging.
                //Something went wrong with the sql filtering and an exception was thrown and caught, .NET filtering will need to be done
                items = new ContactsView(command.LoginUser);

                if (orderByDateCreated)
                {
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID, "DateCreated DESC", limitNumber);
                }
                else
                {
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID);
                }

                xmlString = items.GetXml("Contacts", "Contact", true, command.Filters);
                ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestContacts. GetItems(). SQL filtering generation failed, fell into old method.");
            }

            return(xmlString);
        }
Exemplo n.º 4
0
        public string GetScheduledReports()
        {
            List <ScheduledReportItem> result  = new List <ScheduledReportItem>();
            ScheduledReports           reports = new ScheduledReports(TSAuthentication.GetLoginUser());

            try
            {
                reports.LoadAll(TSAuthentication.OrganizationID);

                foreach (ScheduledReport report in reports)
                {
                    result.Add(new ScheduledReportItem(report));
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), ex, "ReportService.GetScheduledReports");
            }

            return(JsonConvert.SerializeObject(result));
        }
        public static void GetCustomSqlForExport(LoginUser loginUser, SqlCommand command, bool useUserFilter, Report report)
        {
            //if (isSchemaOnly)
            //{
            //    command.CommandText = string.Format("WITH q AS ({0}) SELECT * FROM q WHERE (0=1)", Query);
            //    return;
            //}

            report = Reports.GetReport(loginUser, report.ReportID, loginUser.UserID);
            if (report != null && report.Row["Settings"] != DBNull.Value)
            {
                try
                {
                    UserTabularSettings userFilters = JsonConvert.DeserializeObject <UserTabularSettings>((string)report.Row["Settings"]);
                    StringBuilder       builder     = new StringBuilder();
                    if (userFilters != null && userFilters.Filters != null && userFilters.Filters.Length > 0)
                    {
                        Report.GetWhereClause(loginUser, command, builder, userFilters.Filters);
                        builder.Remove(0, 4);
                        //command.CommandText = string.Format("c AS ({0}), q AS (SELECT * FROM c WHERE {1})", Query, builder.ToString());
                        command.CommandText = string.Format("WITH c AS ({0}) SELECT * FROM c WHERE {1}", report.Query, builder.ToString());
                    }
                    else
                    {
                        //command.CommandText = string.Format("c AS ({0}), q AS (SELECT * FROM c)", Query);
                        command.CommandText = report.Query;
                    }
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(loginUser, ex, "Tabular SQL - User filters");
                    throw;
                }
            }
            else
            {
                //command.CommandText = string.Format("c AS ({0}), q AS (SELECT * FROM c)", Query);
                command.CommandText = report.Query;
            }
        }
Exemplo n.º 6
0
        private void ProcessOrganization(Organization org, bool isRebuilder)
        {
            try
            {
                LogVerbose("");
                LogVerbose("");
                if (isRebuilder)
                {
                    LogVerbose(string.Format("Started rebuilding index for org: {0}", org.OrganizationID.ToString()));
                }
                else
                {
                    LogVerbose(string.Format("Started Indexing for org: {0}", org.OrganizationID.ToString()));
                }

                ProcessIndex(org, ReferenceType.Tickets, isRebuilder);
                ProcessIndex(org, ReferenceType.Wikis, isRebuilder);
                ProcessIndex(org, ReferenceType.Notes, isRebuilder);
                ProcessIndex(org, ReferenceType.ProductVersions, isRebuilder);
                ProcessIndex(org, ReferenceType.WaterCooler, isRebuilder);
                ProcessIndex(org, ReferenceType.Organizations, isRebuilder);
                ProcessIndex(org, ReferenceType.Contacts, isRebuilder);
                ProcessIndex(org, ReferenceType.Assets, isRebuilder);
                ProcessIndex(org, ReferenceType.Products, isRebuilder);
                ProcessIndex(org, ReferenceType.Tasks, isRebuilder);
                LogVerbose("Finished Processing");

                if (isRebuilder && !IsStopped)
                {
                    org.LastIndexRebuilt = DateTime.UtcNow;
                    LogVerbose("LastIndexRebuilt Updated");
                    org.Collection.Save();
                }
            }
            catch (Exception ex)
            {
                Logs.WriteException(ex);
                ExceptionLogs.LogException(LoginUser, ex, "Indexer");
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// 作者:Kylin
 /// 时间:2014.08.26
 /// 描述:创建SA下学员学习累积进度详情
 /// </summary>
 /// <param name="list"></param>
 /// <returns></returns>
 public static bool CreateSAStudentStudyProgressDetail(List<StudentStudyProgressDetail> list)
 {
     try
     {
         using (var edb = new EmeReportsEntities())
         {
             // using (var tran = new TransactionScope(TransactionScopeOption.Required))
             {
                 foreach (var model in list)
                 {
                     if (
                         !edb.StudentStudyProgressDetail.Any(p => p.BranchId == model.BranchId && p.SAId == model.SAId && EntityFunctions.DiffDays(p.OprDate, model.OprDate) == 0 && p.ProductSCode == model.ProductSCode && p.RateCourses == model.RateCourses.Value))
                     {
                         edb.Entry(model).State = EntityState.Added;
                     }
                 }
                 var result = edb.SaveChanges() > 0;
                 // tran.Complete();
                 return result;
             }
         }
     }
     catch (Exception ex)
     {
         var edb = new EmeLogsEntities();
         var exceptrionLog = new ExceptionLogs()
         {
             ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
             Message = string.Format("ServiceReportBLL-CreateSAStudentStudyProgressDetail:{0};{1};{2}", ex.Message, ex.InnerException.Message, ex.HelpLink),
             IsTreat = false,
             CreateBy = null,
             CreateTime = DateTime.Now
         };
         edb.Entry(exceptrionLog).State = EntityState.Added;
         edb.SaveChanges();
         return false;
     }
 }
Exemplo n.º 8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string result = "Please let TeamSupport know about this error.";

        try
        {
            Exception lastException = Server.GetLastError().GetBaseException();

            if (lastException != null && UserSession.LoginUser != null)
            {
                ExceptionLog log = ExceptionLogs.LogException(UserSession.LoginUser, lastException, HttpContext.Current.Request.Url.AbsolutePath, "Oops Page");
                if (log != null)
                {
                    result = "Please let TeamSupport know about this error, and that the error reference number is <span class=\"error\">" + log.ExceptionLogID.ToString() + "</span>";
                }
            }
        }
        catch (Exception)
        {
        }

        litProblem.Text = result;
    }
Exemplo n.º 9
0
        public async Task <string> FetchDeflections(int organization, string phrase, int?customerHubID)
        {
            try
            {
                List <DeflectorReturn> filteredList = new List <DeflectorReturn>();

                if (Convert.ToBoolean(OrganizationSettings.ReadString(LoginUser.Anonymous, organization, "ChatTicketDeflectionEnabled", "False")))
                {
                    //Customer Hub
                    if (customerHubID != null)
                    {
                        filteredList = Deflector.FetchHubDeflections(organization, phrase, (int)customerHubID);
                    }
                    //Portal
                }

                return(JsonConvert.SerializeObject(filteredList));
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(LoginUser.Anonymous, ex, "Deflector");
                return("[]");
            }
        }
Exemplo n.º 10
0
        public bool SetScheduledReportIsActive(int scheduledReportId, bool isActive)
        {
            bool isSuccessful = false;

            try
            {
                LoginUser        loginUser        = TSAuthentication.GetLoginUser();
                ScheduledReports scheduledReports = new ScheduledReports(loginUser);
                scheduledReports.LoadById(scheduledReportId);

                if (scheduledReports != null && scheduledReports.Any())
                {
                    scheduledReports[0].IsActive = isActive;

                    if (!isActive)
                    {
                        scheduledReports[0].NextRun = null;
                    }
                    else
                    {
                        scheduledReports[0].SetNextRun();
                    }

                    scheduledReports[0].ModifierId = loginUser.UserID;
                    scheduledReports.Save();
                    isSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                isSuccessful = false;
                ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), ex, "ReportService.SetScheduledReportIsActive");
            }

            return(isSuccessful);
        }
        public override void Run()
        {
            try
            {
                UpdateHealth();
                if (Settings.ReadBool("CustomerInsights Enabled", true))
                {
                    InitializeGlobalVariables();
                    int customerInsightsInterval = Settings.ReadInt(_intervalKey, 60);

                    if (_lastProcessed.AddMinutes(customerInsightsInterval) < DateTime.UtcNow)
                    {
                        SetValuesFromAccountStats();
                        ProcessCustomerInsights();
                        ResetCurrentApiCalls();
                        Settings.WriteString(_lastProcessedKey, DateTime.UtcNow.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(LoginUser, ex, "CustomerInsightsProcessor");
            }
        }
Exemplo n.º 12
0
        public void NewThread(int messageID, string organizationID)
        {
            LoginUser loginUser = new LoginUser(connString, -1, -1, null);

            try
            {
                loginUser = new LoginUser(connString, TSAuthentication.GetLoginUser().UserID, TSAuthentication.GetLoginUser().OrganizationID, null);
                WaterCoolerThread thread = new WaterCoolerThread();

                WaterCoolerView wcv = new WaterCoolerView(loginUser);
                wcv.LoadByMessageID(messageID);

                WaterCoolerView replies = new WaterCoolerView(loginUser);
                replies.LoadReplies(messageID);

                WatercoolerAttachments wcgroups = new WatercoolerAttachments(loginUser);
                wcgroups.LoadByType(messageID, WaterCoolerAttachmentType.Group);

                WatercoolerAttachments wctickets = new WatercoolerAttachments(loginUser);
                wctickets.LoadByType(messageID, WaterCoolerAttachmentType.Ticket);

                WatercoolerAttachments wcprods = new WatercoolerAttachments(loginUser);
                wcprods.LoadByType(messageID, WaterCoolerAttachmentType.Product);

                WatercoolerAttachments wccompany = new WatercoolerAttachments(loginUser);
                wccompany.LoadByType(messageID, WaterCoolerAttachmentType.Company);

                WatercoolerAttachments wcuseratt = new WatercoolerAttachments(loginUser);
                wcuseratt.LoadByType(messageID, WaterCoolerAttachmentType.User);

                WatercoolerAttachments wcactivitiesatt = new WatercoolerAttachments(loginUser);
                wcactivitiesatt.LoadByType(messageID, WaterCoolerAttachmentType.Activities);

                thread.Message    = wcv.GetWaterCoolerViewItemProxies()[0];
                thread.Replies    = replies.GetWaterCoolerViewItemProxies();
                thread.Groups     = wcgroups.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Group);
                thread.Tickets    = wctickets.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Ticket);
                thread.Products   = wcprods.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Product);
                thread.Company    = wccompany.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Company);
                thread.User       = wcuseratt.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.User);
                thread.Activities = wcactivitiesatt.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Activities);

                //If this is a new thread
                if (thread.Message.MessageParent == -1)
                {
                    var result = pusher.Trigger("ticket-dispatch-" + organizationID, "addThread", thread);
                    //return JsonConvert.SerializeObject(true);
                    //Clients.Group().addThread(thread);
                }
                else
                {
                    var result = pusher.Trigger("ticket-dispatch-" + organizationID, "addComment", thread);
                    //Clients.Group(organizationID).addComment(thread);
                    int parentThreadID = (int)thread.Message.MessageParent;

                    WaterCoolerThread parentThread    = new WaterCoolerThread();
                    WaterCoolerView   parentThreadwcv = new WaterCoolerView(loginUser);
                    parentThreadwcv.LoadByMessageID(parentThreadID);

                    WatercoolerAttachments parentThreadwcgroups = new WatercoolerAttachments(loginUser);
                    parentThreadwcgroups.LoadByType(parentThreadID, WaterCoolerAttachmentType.Group);

                    WatercoolerAttachments parentThreadwctickets = new WatercoolerAttachments(loginUser);
                    parentThreadwctickets.LoadByType(parentThreadID, WaterCoolerAttachmentType.Ticket);

                    WatercoolerAttachments parentThreadwcprods = new WatercoolerAttachments(loginUser);
                    parentThreadwcprods.LoadByType(parentThreadID, WaterCoolerAttachmentType.Product);

                    WatercoolerAttachments parentThreadwccompany = new WatercoolerAttachments(loginUser);
                    parentThreadwccompany.LoadByType(parentThreadID, WaterCoolerAttachmentType.Company);

                    WatercoolerAttachments parentThreadwcuseratt = new WatercoolerAttachments(loginUser);
                    parentThreadwcuseratt.LoadByType(parentThreadID, WaterCoolerAttachmentType.User);

                    WatercoolerAttachments parentThreadactivitiesatt = new WatercoolerAttachments(TSAuthentication.GetLoginUser());
                    parentThreadactivitiesatt.LoadByType(parentThreadID, WaterCoolerAttachmentType.Activities);

                    parentThread.Message    = parentThreadwcv.GetWaterCoolerViewItemProxies()[0];
                    parentThread.Groups     = parentThreadwcgroups.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Group);
                    parentThread.Tickets    = parentThreadwctickets.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Ticket);
                    parentThread.Products   = parentThreadwcprods.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Product);
                    parentThread.Company    = parentThreadwccompany.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Company);
                    parentThread.User       = parentThreadwcuseratt.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.User);
                    parentThread.Activities = parentThreadactivitiesatt.GetWatercoolerAttachmentProxies(WaterCoolerAttachmentType.Activities);

                    result = pusher.Trigger("ticket-dispatch-" + organizationID, "updateattachments", parentThread);
                    //Clients.Group(organizationID).updateattachments(parentThread);
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(loginUser, ex, "Socket.NewThread");
            }
        }
Exemplo n.º 13
0
        private static void SyncNewOrg(HttpContext context)
        {
            /*
             * payload.OrganizationID = orgID;
             * payload.Company = company;
             * payload.UserID = userID;
             * payload.FirstName = firstName;
             * payload.LastName = lastName;
             * payload.Email = email;
             * payload.PhoneNumber = phoneNumber;
             * payload.ProductType = (int)productType;
             * payload.Promo = promo;
             * payload.HubSpotUtk = hubSpotUtk;
             * payload.Source = source;
             * payload.Campaign = campaign;
             * payload.PodName = SystemSettings.GetPodName();
             * payload.Key = "81f4060c-2166-48c3-a126-b12c94f1fd9d";
             * payload.PotentialSeats = 0;
             *
             */
            try
            {
                dynamic data = JObject.Parse(ReadJsonData(context));
                if (data.Key != "81f4060c-2166-48c3-a126-b12c94f1fd9d")
                {
                    return;
                }

                LoginUser    loginUser = LoginUser.Anonymous;
                Organization tsOrg     = (new Organizations(loginUser)).AddNewOrganization();
                tsOrg.ParentID        = 1078;
                tsOrg.Name            = data.Company;
                tsOrg.ImportID        = data.PodName.ToString() + "-" + data.OrganizationID.ToString();
                tsOrg.HasPortalAccess = true;
                tsOrg.IsActive        = true;
                tsOrg.PotentialSeats  = data.PotentialSeats;
                tsOrg.Collection.Save();

                User tsUser = (new Users(loginUser)).AddNewUser();
                tsUser.OrganizationID = tsOrg.OrganizationID;
                tsUser.FirstName      = data.FirstName.ToString();
                tsUser.LastName       = data.LastName.ToString();
                tsUser.Email          = data.Email.ToString();
                tsUser.IsActive       = true;
                tsUser.IsPortalUser   = true;
                tsUser.ImportID       = data.UserID.ToString();
                tsUser.Collection.Save();

                tsOrg.PrimaryUserID = tsUser.UserID;
                tsOrg.Collection.Save();

                PhoneNumber phone = (new PhoneNumbers(loginUser)).AddNewPhoneNumber();
                phone.RefID   = tsOrg.OrganizationID;
                phone.RefType = ReferenceType.Organizations;
                phone.Number  = data.PhoneNumber.ToString();
                phone.Collection.Save();

                OrganizationProducts ops = new OrganizationProducts(loginUser);
                try
                {
                    OrganizationProduct op = ops.AddNewOrganizationProduct();
                    op.OrganizationID    = tsOrg.OrganizationID;
                    op.ProductID         = 219;
                    op.ProductVersionID  = null;
                    op.IsVisibleOnPortal = true;

                    op = ops.AddNewOrganizationProduct();
                    op.OrganizationID    = tsOrg.OrganizationID;
                    op.ProductID         = 44639;
                    op.ProductVersionID  = null;
                    op.IsVisibleOnPortal = true;
                    ops.Save();
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(loginUser, ex, "signup");
                }

/*                string[] salesGuys = SystemSettings.ReadString(loginUser, "SalesGuys", "Jesus:1045957|Leon:1045958").Split('|');
 *              int nextSalesGuy = int.Parse(SystemSettings.ReadString(loginUser, "NextSalesGuy", "0"));
 *              if (nextSalesGuy >= salesGuys.Length || nextSalesGuy < 0) nextSalesGuy = 0;
 *              string salesGuy = salesGuys[nextSalesGuy].Split(':')[0];
 *              string salesGuyID = salesGuys[nextSalesGuy].Split(':')[1];
 *              nextSalesGuy++;
 *              if (nextSalesGuy >= salesGuys.Length) nextSalesGuy = 0;
 *             SystemSettings.WriteString(loginUser, "NextSalesGuy", nextSalesGuy.ToString());
 */
                string      promo          = data.Promo.ToString();
                string      hubSpotUtk     = data.HubSpotUtk.ToString();
                string      source         = data.Source.ToString();
                string      campaign       = data.Campaign.ToString();
                string      potentialSeats = data.PotentialSeats.ToString();
                ProductType productType    = (ProductType)int.Parse(data.ProductType.ToString());
                string      version        = productType == ProductType.HelpDesk ? "Support Desk" : "Enterprise";


                try
                {
                    CustomFields customFields = new CustomFields(loginUser);
                    customFields.LoadByOrganization(1078);

                    CustomValues.UpdateByAPIFieldName(loginUser, customFields, tsOrg.OrganizationID, "Version", version);
                    CustomValues.UpdateByAPIFieldName(loginUser, customFields, tsOrg.OrganizationID, "PodName", data.PodName.ToString());
                    CustomValues.UpdateByAPIFieldName(loginUser, customFields, tsOrg.OrganizationID, "TeamSupportOrganizationID", data.OrganizationID.ToString());
                    CustomValues.UpdateByAPIFieldName(loginUser, customFields, tsOrg.OrganizationID, "LifecycleStatus", "Trial");
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(loginUser, ex, "SyncOrg - Custom Fields");
                }

                try
                {
                    TSHubSpot.HubspotPost(tsUser.FirstName, tsUser.LastName, tsUser.Email, tsOrg.Name, phone.Number, promo, potentialSeats, source, hubSpotUtk, productType);
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(loginUser, ex, "Sign Up - HubSpot", "UserID: " + tsUser.UserID.ToString());
                }

                try
                {
                    int hrCompanyID = TSHighrise.CreateCompany(tsOrg.Name, phone.Number, tsUser.Email, productType, "", source, campaign, "", new string[] { "trial" });
                    int hrContactID = TSHighrise.CreatePerson(tsUser.FirstName, tsUser.LastName, tsOrg.Name, phone.Number, tsUser.Email, productType, "", source, campaign, "");
                    //1. New Trial Check In:1496359
                    //3. End of trial: 1496361
                    //Eric's ID 159931
                    //TSHighrise.CreateTaskFrame("", "today", "1496359", "Party", hrContactID.ToString(), salesGuyID, true, true);
                    //TSHighrise.CreateTaskDate("", DateTime.Now.AddDays(14), "1496361", "Company", hrCompanyID.ToString(), "159931", true, false);//
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(loginUser, ex, "Sign Up - Highrise", "UserID: " + tsUser.UserID.ToString());
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(LoginUser.Anonymous, ex, "SyncUser");
                throw;
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Processes HTTP web requests directed to this HttpHandler.
        /// </summary>
        /// <param name="context">An HttpContext object that provides references
        /// to the intrinsic server objects (for example, Request, Response,
        /// Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            //http://trunk.tsdev.com/signup/validateCompany?name=Muroc%20Systems,%20Inc.
            string fn = context.Request.Url.Segments[2].ToLower();

            if (fn == "fn/")
            {
                string segment = context.Request.Url.Segments[3].ToLower();
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.AddHeader("Expires", "-1");
                context.Response.AddHeader("Pragma", "no-cache");


                if (segment == "validatecompany")
                {
                    ValidateCompany(context);
                }
                else if (segment == "syncuser")
                {
                    SyncUser(context);
                }
                else if (segment == "syncuseremail")
                {
                    SyncUserEmail(context);
                }
                else if (segment == "syncneworg")
                {
                    SyncNewOrg(context);
                }
                else if (segment == "syncorg")
                {
                    SyncOrg(context);
                }
                else if (segment == "post")
                {
                    try
                    {
                        using (Stream receiveStream = context.Request.InputStream)
                        {
                            using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                            {
                                string requestContent      = readStream.ReadToEnd();
                                NameValueCollection values = HttpUtility.ParseQueryString(requestContent);
                                try
                                {
                                    User   user = ProcessSignUp(context, values);
                                    string url  = string.Format("{0}://{1}/{2}?userid={3}", context.Request.UrlReferrer.Scheme, context.Request.UrlReferrer.Host, GetValueString(values["success"]), user.UserID.ToString());
                                    context.Response.Redirect(url, false);
                                }
                                catch (Exception ex)
                                {
                                    ExceptionLogs.LogException(LoginUser.Anonymous, ex, "SIGN UP", requestContent);
                                    context.Response.Redirect(GetErrorUrl(context, values), false);
                                }
                            }
                        }
                    }
                    catch (Exception ex2)
                    {
                        ExceptionLogs.LogException(LoginUser.Anonymous, ex2, "SIGN UP");
                        context.Response.Redirect(GetErrorUrl(context), false);
                    }
                }
            }
        }
        /// <summary>
        /// Finds and sets the Organization fields ids by searching their name
        /// </summary>
        /// <param name="command">Command received in the request to read and process the data in the request body.</param>
        /// <param name="organizationId">OrganizationId to update its record.</param>
        private static void SetFieldIdsByName(RestCommand command, ref Organization organization)
        {
            try
            {
                //Add as necessary to the list and then to the switch-case below for the work to update it.
                List <string> fields = new List <string>()
                {
                    "slaname", "defaultsupportgroup", "defaultsupportuser"
                };

                foreach (string field in fields.Select(p => p.ToLower()).ToList())
                {
                    XmlNode node = GetNode(command, field);

                    if (node != null)
                    {
                        switch (field)
                        {
                        case "slaname":
                            string slaName        = node.InnerText;
                            int?   slaLevelId     = SlaLevel.GetIDByName(command.LoginUser, slaName, null);
                            bool   wasFoundByName = false;

                            if (slaLevelId != null)
                            {
                                //check if id belongs to org
                                SlaLevel slaLevel = SlaLevels.GetSlaLevel(command.LoginUser, (int)slaLevelId);

                                if (slaLevel.OrganizationID == organization.ParentID)
                                {
                                    organization.SlaLevelID = slaLevel.SlaLevelID;
                                    wasFoundByName          = true;
                                }
                            }

                            if (!wasFoundByName)
                            {
                                //check if also the SlaLevelId was sent and it's different than current
                                string  slaLevelIdField = "slalevelid";
                                XmlNode nodeSlaLevelId  = GetNode(command, slaLevelIdField);

                                if (nodeSlaLevelId != null)
                                {
                                    string slaLevelIdText = nodeSlaLevelId.InnerText;
                                    int    slaIdSent      = 0;

                                    if (int.TryParse(slaLevelIdText, out slaIdSent))
                                    {
                                        //check if id belongs to org
                                        SlaLevel slaLevel = SlaLevels.GetSlaLevel(command.LoginUser, slaIdSent);

                                        if (slaLevel != null && slaLevel.OrganizationID == organization.ParentID)
                                        {
                                            organization.SlaLevelID = slaLevel.SlaLevelID;
                                        }
                                        else
                                        {
                                            int?currentSlaLevelId = Organizations.GetOrganization(command.LoginUser, organization.OrganizationID).SlaLevelID;
                                            organization.SlaLevelID = currentSlaLevelId;
                                        }
                                    }
                                }
                            }

                            break;

                        //ToDo: DefaultSupportGroup, DefaultSupportUser
                        default:
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(command.LoginUser, ex, "API", string.Format("OrgID: {0}{1}Verb: {2}{1}Url: {3}{1}Body: {4}", command.Organization.OrganizationID, Environment.NewLine, command.Method, command.Method, command.Data));
            }
        }
Exemplo n.º 16
0
        public override void Run()
        {
            try
            {
                SlaTickets slaTickets = new SlaTickets(LoginUser);
                slaTickets.LoadPending();

                if (slaTickets != null && slaTickets.Count > 0)
                {
                    Logs.WriteEvent(string.Format("{0} pending tickets to calculate the SLA values for.", slaTickets.Count));
                }

                foreach (SlaTicket slaTicket in slaTickets)
                {
                    if (IsStopped)
                    {
                        break;
                    }
                    UpdateHealth();

                    try
                    {
                        Ticket ticket = Tickets.GetTicket(LoginUser, slaTicket.TicketId);

                        if (ticket != null)
                        {
                            bool     isStatusPaused                 = ticket.IsSlaStatusPaused();
                            bool     isClosed                       = ticket.DateClosed != null;
                            DateTime?newSlaViolationTimeClosed      = null;
                            DateTime?newSlaWarningTimeClosed        = null;
                            DateTime?newSlaViolationLastAction      = null;
                            DateTime?newSlaWarningLastAction        = null;
                            DateTime?newSlaViolationInitialResponse = null;
                            DateTime?newSlaWarningInitialResponse   = null;

                            if (!isClosed && !isStatusPaused)
                            {
                                DateTime?lastActionDateCreated = Actions.GetLastActionDateCreated(LoginUser, ticket.TicketID);
                                int      totalActions          = Actions.TotalActionsForSla(LoginUser, ticket.TicketID, ticket.OrganizationID);

                                Organization organization = Organizations.GetOrganization(LoginUser, ticket.OrganizationID);
                                SlaTrigger   slaTrigger   = SlaTriggers.GetSlaTrigger(LoginUser, slaTicket.SlaTriggerId);

                                if (slaTrigger == null)
                                {
                                    Logs.WriteEventFormat("Trigger {0} not found.", slaTicket.SlaTriggerId);
                                }

                                SlaTickets.BusinessHours businessHours = new SlaTickets.BusinessHours()
                                {
                                    DayStartUtc  = organization.BusinessDayStartUtc,
                                    DayEndUtc    = organization.BusinessDayEndUtc,
                                    BusinessDays = organization.BusinessDays
                                };

                                //Check if we should use SLA's business hours instead of Account's
                                if (!slaTrigger.UseBusinessHours &&
                                    !slaTrigger.NoBusinessHours &&
                                    slaTrigger.DayStartUtc.HasValue &&
                                    slaTrigger.DayEndUtc.HasValue)
                                {
                                    businessHours.DayStartUtc  = slaTrigger.DayStartUtc.Value;
                                    businessHours.DayEndUtc    = slaTrigger.DayEndUtc.Value;
                                    businessHours.BusinessDays = slaTrigger.Weekdays;
                                }
                                else if (!slaTrigger.UseBusinessHours && !slaTrigger.NoBusinessHours)
                                {
                                    Logs.WriteEventFormat("Using Account's business hours {0} to {1} because while the trigger is set to use sla's business hours one of them has no value. Sla DayStartUtc {2}, Sla DayEndUtc {3}",
                                                          organization.BusinessDayStartUtc.ToShortTimeString(),
                                                          organization.BusinessDayEndUtc.ToShortTimeString(),
                                                          slaTrigger.DayStartUtc.HasValue ? slaTrigger.DayStartUtc.Value.ToShortTimeString() : "NULL",
                                                          slaTrigger.DayEndUtc.HasValue ? slaTrigger.DayEndUtc.Value.ToShortTimeString() : "NULL");
                                }

                                Logs.WriteEvent(string.Format("Ticket #{0} id {1}. LastAction: {2}, TotalActions: {3}, Org({4}) {5}, SlaTriggerId {6}.", ticket.TicketNumber,
                                                              ticket.TicketID,
                                                              lastActionDateCreated == null ? "none" : lastActionDateCreated.Value.ToString(),
                                                              totalActions,
                                                              organization.OrganizationID,
                                                              organization.Name,
                                                              slaTrigger.SlaTriggerID));
                                List <DateTime> daysToPause    = SlaTriggers.GetSpecificDaysToPause(slaTrigger.SlaTriggerID);
                                bool            pauseOnHoliday = slaTrigger.PauseOnHoliday;
                                CalendarEvents  holidays       = new CalendarEvents(LoginUser);

                                if (pauseOnHoliday)
                                {
                                    holidays.LoadHolidays(organization.OrganizationID);
                                }

                                Dictionary <int, double> businessPausedTimes = new Dictionary <int, double>();

                                //We need to have two calculations for the paused time, one for the Time To Close and Initial Response which should count the paused time since the Ticket creation
                                //and another one for Last Action where it should only count starting from the last action added
                                TimeSpan totalPausedTimeSpan = SlaTickets.CalculatePausedTime(ticket.TicketID, organization, businessHours, slaTrigger, daysToPause, holidays, LoginUser, businessPausedTimes, Logs);
                                Logs.WriteEventFormat("Total Paused Time: {0}", totalPausedTimeSpan.ToString());

                                UpdateBusinessPausedTimes(LoginUser, businessPausedTimes);

                                newSlaViolationTimeClosed = SlaTickets.CalculateSLA(ticket.DateCreatedUtc, businessHours, slaTrigger, slaTrigger.TimeToClose, totalPausedTimeSpan, daysToPause, holidays);

                                if (newSlaViolationTimeClosed != null)
                                {
                                    newSlaWarningTimeClosed = SlaTickets.CalculateSLAWarning(newSlaViolationTimeClosed.Value,
                                                                                             businessHours,
                                                                                             slaTrigger.NoBusinessHours,
                                                                                             slaTrigger.TimeToClose,
                                                                                             slaTrigger.WarningTime,
                                                                                             daysToPause,
                                                                                             holidays);
                                }

                                TimeSpan pausedTimeSpanSinceLastAction = SlaTickets.CalculatePausedTime(ticket.TicketID,
                                                                                                        organization, businessHours,
                                                                                                        slaTrigger,
                                                                                                        daysToPause,
                                                                                                        holidays,
                                                                                                        LoginUser,
                                                                                                        businessPausedTimes,
                                                                                                        Logs,
                                                                                                        false,
                                                                                                        lastActionDateCreated.HasValue ? lastActionDateCreated.Value : (DateTime?)null);
                                Logs.WriteEventFormat("Total Paused Time: {0}", pausedTimeSpanSinceLastAction.ToString());

                                if (lastActionDateCreated == null)
                                {
                                    newSlaViolationLastAction = null;
                                    newSlaWarningLastAction   = null;
                                }
                                else
                                {
                                    newSlaViolationLastAction = SlaTickets.CalculateSLA(lastActionDateCreated.Value,
                                                                                        businessHours,
                                                                                        slaTrigger,
                                                                                        slaTrigger.TimeLastAction,
                                                                                        pausedTimeSpanSinceLastAction,
                                                                                        daysToPause,
                                                                                        holidays);

                                    if (newSlaViolationLastAction != null)
                                    {
                                        newSlaWarningLastAction = SlaTickets.CalculateSLAWarning((DateTime)newSlaViolationLastAction.Value,
                                                                                                 businessHours,
                                                                                                 slaTrigger.NoBusinessHours,
                                                                                                 slaTrigger.TimeLastAction,
                                                                                                 slaTrigger.WarningTime,
                                                                                                 daysToPause,
                                                                                                 holidays);
                                    }
                                }

                                if (slaTrigger.TimeInitialResponse < 1 || totalActions > 0)
                                {
                                    newSlaViolationInitialResponse = null;
                                    newSlaWarningInitialResponse   = null;
                                }
                                else
                                {
                                    newSlaViolationInitialResponse = SlaTickets.CalculateSLA(ticket.DateCreatedUtc,
                                                                                             businessHours,
                                                                                             slaTrigger,
                                                                                             slaTrigger.TimeInitialResponse,
                                                                                             totalPausedTimeSpan,
                                                                                             daysToPause,
                                                                                             holidays);

                                    if (newSlaViolationInitialResponse != null)
                                    {
                                        newSlaWarningInitialResponse = SlaTickets.CalculateSLAWarning((DateTime)newSlaViolationInitialResponse.Value,
                                                                                                      businessHours,
                                                                                                      slaTrigger.NoBusinessHours,
                                                                                                      slaTrigger.TimeInitialResponse,
                                                                                                      slaTrigger.WarningTime,
                                                                                                      daysToPause,
                                                                                                      holidays);
                                    }
                                }
                            }
                            else
                            {
                                Logs.WriteEventFormat("Ticket is {0}, clearing its SLA values.", isClosed ? "Closed" : "Status Paused");
                            }

                            if (HasAnySlaChanges(ticket,
                                                 newSlaViolationTimeClosed,
                                                 newSlaWarningTimeClosed,
                                                 newSlaViolationLastAction,
                                                 newSlaWarningLastAction,
                                                 newSlaViolationInitialResponse,
                                                 newSlaWarningInitialResponse))
                            {
                                ticket.SlaViolationTimeClosed      = newSlaViolationTimeClosed;
                                ticket.SlaWarningTimeClosed        = newSlaWarningTimeClosed;
                                ticket.SlaViolationLastAction      = newSlaViolationLastAction;
                                ticket.SlaWarningLastAction        = newSlaWarningLastAction;
                                ticket.SlaViolationInitialResponse = newSlaViolationInitialResponse;
                                ticket.SlaWarningInitialResponse   = newSlaWarningInitialResponse;
                                Tickets.UpdateTicketSla(LoginUser,
                                                        ticket.TicketID,
                                                        newSlaViolationInitialResponse,
                                                        newSlaViolationLastAction,
                                                        newSlaViolationTimeClosed,
                                                        newSlaWarningInitialResponse,
                                                        newSlaWarningLastAction,
                                                        newSlaWarningTimeClosed);
                                Logs.WriteEvent("Ticket SLA calculation completed.");

                                string signalRUrl = Settings.ReadString("SignalRUrl");

                                if (!string.IsNullOrEmpty(signalRUrl))
                                {
                                    //Dictionary<string, string> queryStringData = new Dictionary<string, string>();
                                    //queryStringData.Add("userID", "-1");
                                    //queryStringData.Add("organizationID", ticket.OrganizationID.ToString());
                                    //HubConnection connection = new HubConnection(signalRUrl, queryStringData);
                                    //IHubProxy signalRConnection = connection.CreateHubProxy("TicketSocket");

                                    //try
                                    //{
                                    //    connection.Start().Wait();
                                    //    signalRConnection.Invoke("RefreshSLA", ticket.TicketNumber);
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //    Logs.WriteEvent("Could not send signalR to refresh the SLA. Message: " + ex.Message);
                                    //}
                                }
                            }
                            else
                            {
                                Logs.WriteEvent("Ticket SLA calculation completed. SLA values did not change, ticket was not updated.");
                            }

                            slaTicket.IsPending = false;
                            slaTicket.Collection.Save();
                        }
                        else
                        {
                            SlaPausedTimes slaPausedTimes = new SlaPausedTimes(LoginUser);
                            slaPausedTimes.LoadByTicketId(slaTicket.TicketId);
                            slaPausedTimes.DeleteAll();
                            slaPausedTimes.Save();

                            slaTicket.Delete();
                            slaTicket.Collection.Save();
                            Logs.WriteEventFormat("Ticket id {0} does not exist anymore, deleted from SlaTickets.", slaTicket.TicketId);
                        }

                        System.Threading.Thread.Sleep(100);
                    }
                    catch (System.Data.SqlClient.SqlException sqlEx)
                    {
                        //Handle the deadlock exception, any other bubble up.
                        if (sqlEx.Number == 1205 || sqlEx.Message.Contains("deadlocked"))
                        {
                            ExceptionLogs.LogException(LoginUser, sqlEx, "SLA Calculator", "Sync");
                            Logs.WriteEventFormat("Exception. Message {0}{1}StackTrace {2}", sqlEx.Message, Environment.NewLine, sqlEx.StackTrace);
                            slaTicket.IsPending = true;
                            slaTicket.Collection.Save();
                            Logs.WriteEventFormat("SlaTicket: TicketId {0} TriggerId {1} still pending.", slaTicket.TicketId, slaTicket.SlaTriggerId);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogs.LogException(LoginUser, ex, "SLA Calculator", "Sync");
                        Logs.WriteEventFormat("Exception. Message {0}{1}StackTrace {2}", ex.Message, Environment.NewLine, ex.StackTrace);

                        slaTicket.IsPending = false;
                        slaTicket.Collection.Save();
                        Logs.WriteEventFormat("SlaTicket: TicketId {0} TriggerId {1} set to not pending.", slaTicket.TicketId, slaTicket.SlaTriggerId);
                    }
                }

                if (slaTickets != null && slaTickets.Count > 0)
                {
                    Logs.WriteEvent(string.Format("Completed processing the {0} pending tickets to calculate the SLA values for.", slaTickets.Count));
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(LoginUser, ex, "SLA Calculator", "Sync");
                Logs.WriteEvent(string.Format("Exception. Message {0}{1}StackTrace {2}", ex.Message, Environment.NewLine, ex.StackTrace));
            }
        }
Exemplo n.º 17
0
        public override void Run()
        {
            ScheduledReports.UnlockThread(LoginUser, (int)_threadPosition);

            while (!IsStopped)
            {
                Logs.WriteHeader("Starting Run");

                try
                {
                    int      waitBeforeLoggingWithoutScheduledReportsDue = 30;
                    DateTime noScheduledReportsDue = DateTime.UtcNow;

                    while (true)
                    {
                        try
                        {
                            if (ServiceStopped)
                            {
                                Logs.WriteHeader("ServiceThread.ServiceStopped");
                                break;
                            }

                            if (IsStopped)
                            {
                                Logs.WriteHeader("IsStopped");
                                break;
                            }

                            ScheduledReport scheduledReport = GetNextScheduledReport(LoginUser.ConnectionString, (int)_threadPosition, Logs);

                            if (scheduledReport != null)
                            {
                                string publicLogPath = TeamSupport.Data.Quarantine.ServiceQ.GetAttachmentPath16(LoginUser, scheduledReport.OrganizationId, scheduledReport.FilePathID);
                                _publicLog = new ReportSenderPublicLog(publicLogPath, scheduledReport.Id, scheduledReport.OrganizationId);
                                Log(string.Format("Date and times used for this log entries are in TimeZone {0}", _publicLog.OrganizationTimeZoneInfo.DisplayName), LogType.Public);
                                QueueEmail(scheduledReport);
                                noScheduledReportsDue = DateTime.UtcNow;
                            }
                            else
                            {
                                if (DateTime.UtcNow.Subtract(noScheduledReportsDue).Minutes >= waitBeforeLoggingWithoutScheduledReportsDue)
                                {
                                    Log(string.Format("No scheduled reports due found in the last {0} minutes", waitBeforeLoggingWithoutScheduledReportsDue));
                                    noScheduledReportsDue = DateTime.UtcNow;
                                }

                                Thread.Sleep(10000);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("Error sending report email - Ending Thread");
                            Logs.WriteException(ex);
                            ExceptionLogs.LogException(LoginUser, ex, "ReportSender", "Error sending report email");
                        }
                        finally
                        {
                            UpdateHealth();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logs.WriteException(ex);
                }
                finally
                {
                    Logs.WriteHeader("Exiting.");
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Populates the fields for multiple objects from the columns found in an open reader.
        /// </summary>
        ///
        /// <param name="rdr" type="IDataReader">An object that implements the IDataReader interface</param>
        ///
        /// <returns>Object of ExceptionLogs</returns>
        ///
        /// <remarks>
        ///
        /// <RevisionHistory>
        /// Author				Date			Description
        /// DLGenerator			07/27/2010 11:57:21 AM		Created function
        /// 
        /// </RevisionHistory>
        ///
        /// </remarks>
        ///
        internal static ExceptionLogs PopulateObjectsFromReaderWithCheckingReader(IDataReader rdr, DatabaseHelper oDatabaseHelper,string connectionstring)
        {
            ExceptionLogs list = new ExceptionLogs();

            if (rdr.Read())
            {
                ExceptionLog obj = new ExceptionLog(connectionstring);
                PopulateObjectFromReader(obj, rdr);
                list.Add(obj);
                while (rdr.Read())
                {
                    obj = new ExceptionLog(connectionstring);
                    PopulateObjectFromReader(obj, rdr);
                    list.Add(obj);
                }
                oDatabaseHelper.Dispose();
                return list;
            }
            else
            {
                oDatabaseHelper.Dispose();
                return null;
            }
        }
Exemplo n.º 19
0
 public void LogException(string message, string location)
 {
     ExceptionLogs.AddLog(TSAuthentication.GetLoginUser(), "Javascript Error", message, location, HttpContext.Current.Request.Url.ToString(), HttpContext.Current.Request.Headers.ToString(), HttpContext.Current.Request.UserAgent);
 }
Exemplo n.º 20
0
        private void RecoverTickets(int orgID, LoginUser loginUser)
        {
            Tickets    badTickets = new Tickets(GetCorrupteLoginUser());
            SqlCommand command    = new SqlCommand();

            command.CommandText = @"
        SELECT 
          * 
        FROM 
          Tickets 
        WHERE 
          OrganizationID = @OrganizationID
          AND DateCreated > '2015-09-17 05:56:00'
          AND TicketSource != 'EMail'
          AND IgnoreMe = 0
      ";
            command.CommandType = CommandType.Text;
            command.Parameters.AddWithValue("@OrganizationID", orgID);
            badTickets.Fill(command, "");

            Organizations existingCompanies = new Organizations(loginUser);

            existingCompanies.LoadByParentID(orgID, false);

            foreach (Ticket badTicket in badTickets)
            {
                try
                {
                    //Copy Ticket
                    Ticket goodTicket = (new Tickets(loginUser)).AddNewTicket();
                    goodTicket.CopyRowData(badTicket);
                    //Product
                    if (badTicket.ProductID != null)
                    {
                        Product goodProduct = _goodProducts.FindByProductID((int)badTicket.ProductID);
                        if (goodProduct == null)
                        {
                            Product badProduct = _badProducts.FindByProductID((int)badTicket.ProductID);
                            goodProduct = _goodProducts.FindByName(badProduct.Name);
                            if (goodProduct != null)
                            {
                                goodTicket.ProductID = goodProduct.ProductID;
                            }
                            else
                            {
                                goodTicket.ProductID = null;
                            }
                        }
                    }
                    //Version
                    if (goodTicket.ProductID != null && badTicket.ReportedVersionID != null)
                    {
                        ProductVersion goodProductVersion = _goodProductVersions.FindByProductVersionID((int)badTicket.ReportedVersionID);
                        if (goodProductVersion == null)
                        {
                            ProductVersion badProductVersion = _badProductVersions.FindByProductVersionID((int)badTicket.ReportedVersionID);
                            goodProductVersion = _goodProductVersions.FindByVersionNumber(badProductVersion.VersionNumber, (int)goodTicket.ProductID);
                            if (goodProductVersion != null)
                            {
                                goodTicket.ReportedVersionID = goodProductVersion.ProductVersionID;
                            }
                            else
                            {
                                goodTicket.ReportedVersionID = null;
                            }
                        }
                    }
                    //Solved Version
                    if (goodTicket.ProductID != null && badTicket.SolvedVersionID != null)
                    {
                        ProductVersion goodProductVersion = _goodProductVersions.FindByProductVersionID((int)badTicket.SolvedVersionID);
                        if (goodProductVersion == null)
                        {
                            ProductVersion badProductVersion = _badProductVersions.FindByProductVersionID((int)badTicket.SolvedVersionID);
                            goodProductVersion = _goodProductVersions.FindByVersionNumber(badProductVersion.VersionNumber, (int)goodTicket.ProductID);
                            if (goodProductVersion != null)
                            {
                                goodTicket.SolvedVersionID = goodProductVersion.ProductVersionID;
                            }
                            else
                            {
                                goodTicket.SolvedVersionID = null;
                            }
                        }
                    }
                    //Group
                    if (badTicket.GroupID != null)
                    {
                        Group goodGroup = _goodGroups.FindByGroupID((int)badTicket.GroupID);
                        if (goodGroup == null)
                        {
                            Group badGroup = _badGroups.FindByGroupID((int)badTicket.GroupID);
                            goodGroup = _goodGroups.FindByName(badGroup.Name);
                            if (goodGroup != null)
                            {
                                goodTicket.GroupID = goodGroup.GroupID;
                            }
                            else
                            {
                                goodTicket.GroupID = null;
                            }
                        }
                    }
                    //Assigned User
                    if (badTicket.UserID != null)
                    {
                        User goodUser = _goodUsers.FindByUserID((int)badTicket.UserID);
                        if (goodUser == null)
                        {
                            User badUser = _badUsers.FindByUserID((int)badTicket.UserID);
                            goodUser = _goodUsers.FindByEmail(badUser.Email);
                            if (goodUser != null)
                            {
                                goodTicket.UserID = goodUser.UserID;
                            }
                            else
                            {
                                goodTicket.UserID = null;
                            }
                        }
                    }
                    //Type
                    TicketType goodTicketType = _goodTicketTypes.FindByTicketTypeID(badTicket.TicketTypeID);
                    if (goodTicketType == null)
                    {
                        TicketType badTicketType = _badTicketTypes.FindByTicketTypeID(badTicket.TicketTypeID);
                        goodTicketType = _goodTicketTypes.FindByName(badTicketType.Name);
                        if (goodTicketType != null)
                        {
                            goodTicket.TicketTypeID = goodTicketType.TicketTypeID;
                        }
                        else
                        {
                            goodTicket.TicketTypeID = _goodTicketTypes[0].TicketTypeID;
                        }
                    }

                    //Status
                    TicketStatus goodTicketStatus = _goodTicketStatuses.FindByTicketStatusID(badTicket.TicketStatusID);
                    if (goodTicketStatus == null)
                    {
                        TicketStatus badTicketStatus = _badTicketStatuses.FindByTicketStatusID(badTicket.TicketStatusID);
                        goodTicketStatus = _goodTicketStatuses.FindByName(badTicketStatus.Name, goodTicket.TicketTypeID);
                        if (goodTicketStatus != null)
                        {
                            goodTicket.TicketStatusID = goodTicketStatus.TicketStatusID;
                        }
                        else
                        {
                            goodTicketStatus          = _goodTicketStatuses.FindTopOne(goodTicket.TicketTypeID);
                            goodTicket.TicketStatusID = goodTicketStatus.TicketStatusID;
                        }
                    }


                    //Severity
                    TicketSeverity goodTicketSeverity = _goodTicketSeverities.FindByTicketSeverityID(badTicket.TicketSeverityID);
                    if (goodTicketSeverity == null)
                    {
                        TicketSeverity badTicketSeverity = _badTicketSeverities.FindByTicketSeverityID(badTicket.TicketSeverityID);
                        goodTicketSeverity = _goodTicketSeverities.FindByName(badTicketSeverity.Name);
                        if (goodTicketSeverity != null)
                        {
                            goodTicket.TicketSeverityID = goodTicketSeverity.TicketSeverityID;
                        }
                        else
                        {
                            goodTicket.TicketSeverityID = _goodTicketSeverities[0].TicketSeverityID;
                        }
                    }

                    //Knowledgebase Cat
                    if (badTicket.KnowledgeBaseCategoryID != null)
                    {
                        KnowledgeBaseCategory goodKBCategory = _goodTicketKBCategories.FindByCategoryID((int)badTicket.KnowledgeBaseCategoryID);
                        if (goodKBCategory == null)
                        {
                            KnowledgeBaseCategory badKBCategory = _badTicketKBCategories.FindByCategoryID((int)badTicket.KnowledgeBaseCategoryID);
                            goodKBCategory = _goodTicketKBCategories.FindByName(badKBCategory.CategoryName);
                            if (goodKBCategory != null)
                            {
                                goodTicket.KnowledgeBaseCategoryID = goodKBCategory.CategoryID;
                            }
                            else
                            {
                                goodTicket.KnowledgeBaseCategoryID = null;
                            }
                        }
                    }

                    //Parent Ticket (NOTE from MT:  we decided as a team to null out this field to ensure no bad relationships can happen since we don't know the ticketID is a preserved field for every ticket.
                    goodTicket.ParentID = null;

                    //Closing User
                    if (badTicket.CloserID != null)
                    {
                        User goodUser = _goodUsers.FindByUserID((int)badTicket.CloserID);
                        if (goodUser == null)
                        {
                            User badUser = _badUsers.FindByUserID((int)badTicket.CloserID);
                            goodUser = _goodUsers.FindByEmail(badUser.Email);
                            if (goodUser != null)
                            {
                                goodTicket.CloserID = goodUser.UserID;
                            }
                            else
                            {
                                goodTicket.CloserID = null;
                            }
                        }
                    }


                    //Reset ticket dates
                    goodTicket.DateCreated  = badTicket.DateCreatedUtc;
                    goodTicket.DateModified = badTicket.DateModifiedUtc;
                    goodTicket.ParentID     = null;
                    goodTicket.ImportID     = _importID;
                    if (badTicket.CreatorID > 0)
                    {
                        User creator = _usersAndContacts.FindByUserID(badTicket.CreatorID);
                        if (creator != null)
                        {
                            goodTicket.CreatorID = creator.UserID;
                        }
                        else
                        {
                            goodTicket.CreatorID = -5;
                        }
                    }
                    else
                    {
                        goodTicket.CreatorID = badTicket.CreatorID;
                    }

                    if (badTicket.ModifierID > 0)
                    {
                        User modifier = _usersAndContacts.FindByUserID(badTicket.ModifierID);
                        if (modifier != null)
                        {
                            goodTicket.ModifierID = modifier.UserID;
                        }
                        else
                        {
                            goodTicket.ModifierID = -5;
                        }
                    }
                    else
                    {
                        goodTicket.ModifierID = badTicket.ModifierID;
                    }
                    goodTicket.TicketNumber = 0;
                    goodTicket.Collection.Save();
                    EmailPosts.DeleteImportEmails(loginUser);

                    Actions badActions = new Actions(GetCorrupteLoginUser());
                    badActions.LoadByTicketID(badTicket.TicketID);

                    foreach (TeamSupport.Data.Action badAction in badActions)
                    {
                        TeamSupport.Data.Action goodAction = new Actions(loginUser).AddNewAction();
                        goodAction.CopyRowData(badAction);
                        goodAction.DateCreated  = badAction.DateCreatedUtc;
                        goodAction.DateModified = badAction.DateCreatedUtc;
                        goodAction.TicketID     = goodTicket.TicketID;
                        goodAction.ImportID     = _importID;
                        if (badAction.CreatorID > 0)
                        {
                            User creator = _usersAndContacts.FindByUserID(badAction.CreatorID);
                            if (creator != null)
                            {
                                goodAction.CreatorID = creator.UserID;
                            }
                            else
                            {
                                goodAction.CreatorID = -5;
                            }
                        }
                        else
                        {
                            goodAction.CreatorID = badAction.CreatorID;
                        }

                        if (badAction.ModifierID > 0)
                        {
                            User modifier = _usersAndContacts.FindByUserID(badAction.ModifierID);
                            if (modifier != null)
                            {
                                goodAction.ModifierID = modifier.UserID;
                            }
                            else
                            {
                                goodAction.ModifierID = -5;
                            }
                        }
                        else
                        {
                            goodAction.ModifierID = badAction.ModifierID;
                        }
                        goodAction.Collection.Save();
                        EmailPosts.DeleteImportEmails(loginUser);
                    }


                    Organizations orgs = new Organizations(GetCorrupteLoginUser());
                    orgs.LoadBTicketID(badTicket.TicketID);

                    foreach (Organization org in orgs)
                    {
                        Organization goodCompany = existingCompanies.FindByName(org.Name);
                        if (org.ParentID == orgID && goodCompany != null)
                        {
                            goodTicket.Collection.AddOrganization(goodCompany.OrganizationID, goodTicket.TicketID);
                            EmailPosts.DeleteImportEmails(loginUser);
                        }
                    }

                    RecoverTicketCustomValues(orgID, badTicket.TicketID, goodTicket.TicketID);
                    EmailPosts.DeleteImportEmails(loginUser);
                }
                catch (Exception ex)
                {
                    _exceptionOcurred = true;
                    ExceptionLogs.LogException(GetCorrupteLoginUser(), ex, "recover");
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            int organizationID = int.Parse(context.Request.Headers["OrganizationID"]);

            try
            {
                _loginUser    = new LoginUser(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MainConnection"].ConnectionString, (int)SystemUser.API, organizationID, null);
                _organization = Organizations.GetOrganization(_loginUser, organizationID);
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(_loginUser, ex, "OrgID: " + organizationID.ToString());
                throw new RestException(HttpStatusCode.Unauthorized);
            }

            ApiLog   log       = new ApiLogs(_loginUser).AddNewApiLog();
            DateTime timeStart = DateTime.Now;

            context.Response.StatusCode  = (int)HttpStatusCode.OK;
            context.Response.ContentType = "text/plain";
            try
            {
                try
                {
                    RestCommand command = new RestCommand(_loginUser, _organization, context);
                    log.OrganizationID = _organization.OrganizationID;
                    log.RequestBody    = command.Data;
                    log.Verb           = context.Request.HttpMethod.ToUpper();
                    log.Url            = context.Request.Url.OriginalString;
                    log.IPAddress      = context.Request.UserHostAddress;
                    RestProcessor processor = new RestProcessor(command);

                    int companyId       = command.IsCustomerOnly ? (int)command.Organization.ParentID : _loginUser.OrganizationID;
                    int apiRequestLimit = command.IsCustomerOnly ? Organizations.GetOrganization(_loginUser, companyId).APIRequestLimit : _organization.APIRequestLimit;
                    int apiRequestCount = ApiLogs.GetDailyRequestCount(_loginUser, companyId);

                    if (ApiLogs.IsUrlBlackListed(_loginUser, _organization.OrganizationID, log.Url) || SystemSettings.GetIsApiDisabled())
                    {
                        string blacklistError = "{ \"Error\": \"This resource is not accessible at this time.\"}";

                        if (command.Format == RestFormat.XML)
                        {
                            System.Xml.XmlDocument xmlDoc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(blacklistError);
                            xmlDoc.XmlResolver = null;
                            blacklistError     = xmlDoc.InnerXml;
                        }

                        throw new RestException(HttpStatusCode.BadRequest, blacklistError);
                    }
                    if (apiRequestCount >= apiRequestLimit)
                    {
                        string requestLimitError = "{ \"Error\": \"You have exceeded your 24 hour API request limit of " + _organization.APIRequestLimit.ToString() + ".\"}";

                        if (command.Format == RestFormat.XML)
                        {
                            System.Xml.XmlDocument xmlDoc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(requestLimitError);
                            xmlDoc.XmlResolver = null;
                            requestLimitError  = xmlDoc.InnerXml;
                        }

                        throw new RestException(HttpStatusCode.Forbidden, requestLimitError);
                    }
                    else
                    {
                        int apiRequestMinuteLimit     = command.IsCustomerOnly ? Organizations.GetOrganization(_loginUser, companyId).APIRequestMinuteLimit : _organization.APIRequestMinuteLimit;
                        int apiRequestLastMinuteCount = ApiLogs.GetLastMinuteRequestCount(_loginUser, companyId);

                        if (apiRequestLastMinuteCount > apiRequestMinuteLimit)
                        {
                            string requestLimitErrorPerMinute = "{ \"Error\": \"You have exceeded your minute API request limit of " + apiRequestMinuteLimit.ToString() + ".\"}";

                            if (command.Format == RestFormat.XML)
                            {
                                System.Xml.XmlDocument xmlDoc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(requestLimitErrorPerMinute);
                                xmlDoc.XmlResolver         = null;
                                requestLimitErrorPerMinute = xmlDoc.InnerXml;
                            }

                            throw new RestException(HttpStatusCode.Forbidden, requestLimitErrorPerMinute);
                        }
                    }

                    processor.Process();
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(_loginUser, ex, "API", string.Format("OrgID: {0}{1}Verb: {2}{1}Url: {3}{1}Body: {4}", log.OrganizationID, Environment.NewLine, log.Verb, log.Url, log.RequestBody));
                    if (ex is System.Data.SqlClient.SqlException && ex.Message.ToLower().Contains("variable names must be unique within a query batch or stored procedure"))
                    {
                        throw new RestException(HttpStatusCode.Unused, "{ Error: 'Filters can't be duplicated' }", ex);
                    }
                    else if (!(ex is RestException))
                    {
                        throw new RestException(HttpStatusCode.InternalServerError, "Internal Server Error: " + ex.Message + ex.StackTrace, ex);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            catch (RestException rex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.StatusCode  = (int)rex.HttpStatusCode;
                log.TimeToComplete           = (int)(DateTime.Now - timeStart).TotalSeconds;
                log.StatusCode = context.Response.StatusCode;
                log.Collection.Save();
                context.Response.ClearContent();
                context.Response.Write(rex.Message);
                context.Response.End();
            }
            log.TimeToComplete = (int)(DateTime.Now - timeStart).TotalSeconds;
            log.StatusCode     = context.Response.StatusCode;
            log.Collection.Save();
            context.Response.End();
        }
Exemplo n.º 22
0
        public int SaveScheduledReport(int scheduledReportId,
                                       int reportId,
                                       string emailSubject,
                                       string emailBody,
                                       string emailAddresses,
                                       Object startOn,
                                       ScheduledReportFrequency frequency,
                                       int every,
                                       int weekday,
                                       int dayOfMonth,
                                       bool isActive)
        {
            try
            {
                LoginUser        loginUser        = TSAuthentication.GetLoginUser();
                ScheduledReports scheduledReports = new ScheduledReports(loginUser);

                if (scheduledReportId == 0)
                {
                    ScheduledReport scheduledReport = scheduledReports.AddNewScheduledReport();
                    scheduledReport.ReportId        = reportId;
                    scheduledReport.EmailSubject    = emailSubject;
                    scheduledReport.EmailBody       = emailBody;
                    scheduledReport.EmailRecipients = emailAddresses;
                    scheduledReport.OrganizationId  = TSAuthentication.OrganizationID;
                    scheduledReport.IsActive        = true;
                    scheduledReport.StartDate       = (DateTime)startOn;
                    scheduledReport.RecurrencyId    = (byte)frequency;
                    scheduledReport.Every           = (byte)every;
                    scheduledReport.Weekday         = (byte)weekday;
                    scheduledReport.Monthday        = (byte)dayOfMonth;
                    scheduledReport.IsActive        = isActive;
                    scheduledReport.FilePathID      = 3;

                    //This needs to be set before SetNextRun because that one needs it to get the timezone to use.
                    scheduledReport.CreatorId = loginUser.UserID;

                    if (isActive)
                    {
                        scheduledReport.SetNextRun();
                    }
                    else
                    {
                        scheduledReport.NextRun = null;
                    }

                    scheduledReport.Collection.Save();

                    scheduledReportId = scheduledReport.Id;
                }
                else
                {
                    scheduledReports.LoadById(scheduledReportId);

                    if (scheduledReports != null && scheduledReports.Any())
                    {
                        scheduledReports[0].EmailSubject    = emailSubject;
                        scheduledReports[0].EmailBody       = emailBody;
                        scheduledReports[0].EmailRecipients = emailAddresses;
                        scheduledReports[0].IsActive        = true;
                        try
                        { scheduledReports[0].StartDate = (DateTime)startOn; }
                        catch (Exception ex) { }
                        scheduledReports[0].RecurrencyId = (byte)frequency;
                        scheduledReports[0].Every        = (byte)every;
                        scheduledReports[0].Weekday      = (byte)weekday;
                        scheduledReports[0].Monthday     = (byte)dayOfMonth;
                        scheduledReports[0].IsActive     = isActive;

                        if (isActive)
                        {
                            scheduledReports[0].SetNextRun();
                        }
                        else
                        {
                            scheduledReports[0].NextRun = null;
                        }

                        scheduledReports[0].ModifierId = loginUser.UserID;
                        scheduledReports.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), ex, "ReportService.SaveScheduledReport");
            }

            return(scheduledReportId);
        }
Exemplo n.º 23
0
        public static string GetTickets(RestCommand command)
        {
            string xml             = "";
            bool   hasBeenFiltered = false;
            int    totalRecords    = 0;

            if (command.IsPaging)
            {
                try
                {
                    TicketsView tickets = new TicketsView(command.LoginUser);
                    tickets.LoadAllTicketIds(command.Organization.OrganizationID, command.Filters, command.PageNumber, command.PageSize);
                    hasBeenFiltered = true;
                    XmlTextWriter writer = Tickets.BeginXmlWrite("Tickets");

                    foreach (int ticketTypeId in tickets.GroupBy(g => g.TicketTypeID).Select(p => p.Key).ToList())
                    {
                        try
                        {
                            TicketsView ticketsResult = new TicketsView(command.LoginUser);
                            ticketsResult.LoadByTicketIDList(command.Organization.OrganizationID, ticketTypeId, tickets.Where(w => w.TicketTypeID == ticketTypeId).Select(p => p.TicketID).ToList());

                            foreach (DataRow row in ticketsResult.Table.Rows)
                            {
                                int  ticketId = (int)row["TicketID"];
                                Tags tags     = new Tags(command.LoginUser);
                                tags.LoadByReference(ReferenceType.Tickets, ticketId);
                                tags = tags ?? new Tags(command.LoginUser);
                                ticketsResult.WriteXml(writer, row, "Ticket", true, !hasBeenFiltered ? command.Filters : new System.Collections.Specialized.NameValueCollection(), tags);
                            }
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestTickets. GetTickets(). Paging.");
                        }
                    }

                    if (tickets.Count > 0)
                    {
                        totalRecords = tickets[0].TotalRecords;
                    }

                    writer.WriteElementString("TotalRecords", totalRecords.ToString());
                    xml = Tickets.EndXmlWrite(writer);
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestTickets. GetTickets(). Paging. SQL filtering generation failed.");
                    throw new RestException(HttpStatusCode.InternalServerError, "There was an error processing your request. Please contact TeamSupport.com", ex);
                }
            }
            else
            {
                //No Paging
                if (command.Filters["TicketTypeID"] != null)
                {
                    try
                    {
                        TicketsView tickets      = new TicketsView(command.LoginUser);
                        int         ticketTypeID = int.Parse(command.Filters["TicketTypeID"]);
                        TicketType  ticketType   = TicketTypes.GetTicketType(command.LoginUser, ticketTypeID);
                        if (ticketType.OrganizationID != command.Organization.OrganizationID)
                        {
                            throw new Exception();
                        }

                        try
                        {
                            tickets.LoadByTicketTypeID(ticketTypeID, command.Organization.OrganizationID, command.Filters);
                        }
                        catch (Exception ex)
                        {
                            //if something fails use the old method
                            tickets.LoadByTicketTypeID(ticketTypeID);
                            ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestTickets. GetTickets(). No Paging. SQL filtering generation failed, fell into old method.");
                        }

                        xml = tickets.GetXml("Tickets", "Ticket", true, command.Filters);
                        xml = AddTagsToTickets(xml, command);
                    }
                    catch (Exception ex)
                    {
                        throw new RestException(HttpStatusCode.NotAcceptable, "Invalid TicketTypeID to filter.", ex);
                    }
                }
                else
                {
                    TicketTypes ticketTypes = new TicketTypes(command.LoginUser);
                    ticketTypes.LoadByOrganizationID(command.Organization.OrganizationID);

                    TicketsView   tickets = new TicketsView(command.LoginUser);
                    XmlTextWriter writer  = Tickets.BeginXmlWrite("Tickets");

                    foreach (TicketType ticketType in ticketTypes)
                    {
                        try
                        {
                            tickets.LoadByTicketTypeID(ticketType.TicketTypeID, command.Organization.OrganizationID, command.Filters);
                        }
                        catch (Exception ex)
                        {
                            if (ex is System.Data.SqlClient.SqlException && ex.Message.ToLower().Contains("variable names must be unique within a query batch or stored procedure"))
                            {
                                throw ex;
                            }
                            else
                            {
                                //if something fails use the old method
                                tickets.LoadByTicketTypeID(ticketType.TicketTypeID);
                                ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestTickets. GetTickets(). No Paging. No TicketTypeId filter. SQL filtering generation failed, fell into old method.");
                            }
                        }

                        foreach (DataRow row in tickets.Table.Rows)
                        {
                            int  ticketId = (int)row["TicketID"];
                            Tags tags     = new Tags(command.LoginUser);
                            tags.LoadByReference(ReferenceType.Tickets, ticketId);
                            tags = tags ?? new Tags(command.LoginUser);
                            tickets.WriteXml(writer, row, "Ticket", true, command.Filters, tags);
                        }
                    }

                    xml = Tickets.EndXmlWrite(writer);
                }
            }

            return(xml);
        }
Exemplo n.º 24
0
        public static string GetCustomerTickets(RestCommand command)
        {
            TicketsView tickets = new TicketsView(command.LoginUser);
            string      xml     = "";

            if (command.Filters["TicketTypeID"] != null)
            {
                try
                {
                    int        ticketTypeID = int.Parse(command.Filters["TicketTypeID"]);
                    TicketType ticketType   = TicketTypes.GetTicketType(command.LoginUser, ticketTypeID);
                    if (ticketType.OrganizationID != command.Organization.ParentID)
                    {
                        throw new Exception();
                    }
                    tickets.LoadByCustomerTicketTypeID(command.Organization.OrganizationID, ticketTypeID);
                }
                catch (Exception ex)
                {
                    throw new RestException(HttpStatusCode.NotAcceptable, ex.Message);
                    throw new RestException(HttpStatusCode.NotAcceptable, "Invalid TicketTypeID to filter.", ex);
                }
            }
            else
            {
                if (command.IsPaging)
                {
                    try
                    {
                        //remove Paging parameters
                        NameValueCollection filters = new NameValueCollection();

                        foreach (string key in command.Filters.AllKeys)
                        {
                            if (key.ToLower() != "pagenumber" && key.ToLower() != "pagesize")
                            {
                                filters.Add(key, command.Filters[key]);
                            }
                        }

                        tickets.LoadByCustomerID(command.Organization.OrganizationID, command.Filters, (int)command.PageNumber, (int)command.PageSize);

                        XmlTextWriter writer = Tickets.BeginXmlWrite("Tickets");

                        foreach (DataRow row in tickets.Table.Rows)
                        {
                            int  ticketId = (int)row["TicketID"];
                            Tags tags     = new Tags(command.LoginUser);
                            tags.LoadByReference(ReferenceType.Tickets, ticketId);
                            tags = tags ?? new Tags(command.LoginUser);
                            tickets.WriteXml(writer, row, "Ticket", true, new NameValueCollection(), tags);
                        }

                        int totalRecords = 0;

                        if (tickets.Count > 0)
                        {
                            totalRecords = tickets[0].TotalRecords;
                        }

                        writer.WriteElementString("TotalRecords", totalRecords.ToString());
                        xml = Tickets.EndXmlWrite(writer);
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestTickets. GetCustomerTickets(). Paging. SQL filtering generation failed.");
                        throw new RestException(HttpStatusCode.InternalServerError, "There was an error processing your request. Please contact TeamSupport.com", ex);
                    }
                }
                else
                {
                    tickets.LoadByCustomerID(command.Organization.OrganizationID);
                    xml = tickets.GetXml("Tickets", "Ticket", true, command.Filters, command.IsPaging);
                    xml = AddTagsToTickets(xml, command, true);
                }
            }

            return(xml);
        }
Exemplo n.º 25
0
        public static string GetDeletedTickets(RestCommand command)
        {
            string xml             = "";
            bool   hasBeenFiltered = false;
            int    totalRecords    = 0;

            DeletedTickets deletedTickets = new DeletedTickets(command.LoginUser);

            if (command.IsPaging)
            {
                try
                {
                    deletedTickets.LoadByOrganizationID(command.Organization.OrganizationID, command.Filters, command.PageNumber, command.PageSize);
                    hasBeenFiltered = true;
                    XmlTextWriter writer = DeletedTickets.BeginXmlWrite("DeletedTicketx");
                    try
                    {
                        foreach (DataRow row in deletedTickets.Table.Rows)
                        {
                            int  recordId = (int)row["ID"];
                            Tags tags     = new Tags(command.LoginUser);
                            tags.LoadByReference(ReferenceType.DeletedTickets, recordId);
                            tags = tags ?? new Tags(command.LoginUser);
                            deletedTickets.WriteXml(writer, row, "DeletedTicket", true, !hasBeenFiltered ? command.Filters : new System.Collections.Specialized.NameValueCollection(), tags);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestDeletedTickets. GetDeletedTickets(). Paging.");
                    }

                    if (deletedTickets.Count > 0)
                    {
                        totalRecords = deletedTickets[0].TotalRecords;
                    }

                    writer.WriteElementString("TotalRecords", totalRecords.ToString());
                    xml = DeletedTickets.EndXmlWrite(writer);
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestDeletedTickets. GetDeletedTickets(). Paging. SQL filtering generation failed.");
                    throw new RestException(HttpStatusCode.InternalServerError, "There was an error processing your request. Please contact TeamSupport.com", ex);
                }
            }
            else
            {
                //No Paging
                try
                {
                    deletedTickets.LoadByOrganizationID(command.Organization.OrganizationID, command.Filters);
                    xml = deletedTickets.GetXml("DeletedTickets", "DeletedTicket", true, command.Filters);
                    //xml = AddTagsToDeletedTickets(xml, command);
                }
                catch (Exception ex)
                {
                    ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestDeletedTickets. GetDeletedTickets(). No Paging. SQL filtering generation failed.");
                }
            }

            return(xml);
        }
Exemplo n.º 26
0
 public int GetExceptionLogCount()
 {
     return(ExceptionLogs.GetCount());
 }
Exemplo n.º 27
0
        /// <summary>
        /// Populates the fields for multiple objects from the columns found in an open reader.
        /// </summary>
        ///
        /// <param name="rdr" type="IDataReader">An object that implements the IDataReader interface</param>
        ///
        /// <returns>Object of ExceptionLogs</returns>
        ///
        /// <remarks>
        ///
        /// <RevisionHistory>
        /// Author				Date			Description
        /// DLGenerator			07/27/2010 11:57:21 AM		Created function
        /// 
        /// </RevisionHistory>
        ///
        /// </remarks>
        ///
        internal static ExceptionLogs PopulateObjectsFromReader(IDataReader rdr,string connectionstring)
        {
            ExceptionLogs list = new ExceptionLogs();

            while (rdr.Read())
            {
                ExceptionLog obj = new ExceptionLog(connectionstring);
                PopulateObjectFromReader(obj,rdr);
                list.Add(obj);
            }
            return list;
        }
Exemplo n.º 28
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.AddHeader("Expires", "-1");
            context.Response.AddHeader("Pragma", "no-cache");

            using (Stream receiveStream = context.Request.InputStream)
            {
                using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    string requestContent = readStream.ReadToEnd();
                    try
                    {
                        List <string> segments = new List <string>();
                        bool          flag     = false;
                        for (int i = 0; i < context.Request.Url.Segments.Length; i++)
                        {
                            string s = context.Request.Url.Segments[i].ToLower().Trim().Replace("/", "");
                            if (flag)
                            {
                                segments.Add(s);
                            }
                            if (s == "reportdata")
                            {
                                flag = true;
                            }
                        }


                        JObject args    = JObject.Parse(requestContent);
                        string  content = "";
                        switch (segments[0])
                        {
                        case "table":
                            content = GetReportTableData(args);
                            break;

                        case "chart":
                            content = GetReportChartData(args);
                            break;

                        default:
                            context.Response.ContentType = "text/html";
                            context.Response.Write("Undefined report data type");
                            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                            context.Response.End();
                            break;
                        }
                        context.Response.ContentType = "application/json; charset=utf-8";
                        context.Response.Write(content);
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), ex, "ReportDataHander", requestContent);
                        context.Response.ContentType = "text/html";
                        context.Response.Write("There was an error getting your report data.");
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    }
                }
            }
        }
Exemplo n.º 29
0
        public void GetSummarySql(SqlCommand command, SummaryReport summaryReport, bool isSchemaOnly, int?reportID, bool useUserFilter, bool useDefaultOrderBy)
        {
            LoginUser         loginUser = _userRights._loginUser;
            StringBuilder     builder   = new StringBuilder();
            ReportSubcategory sub       = ReportSubcategories.GetReportSubcategory(loginUser, summaryReport.Subcategory);
            ReportTables      tables    = new ReportTables(loginUser);

            tables.LoadAll();
            List <DescriptiveClauseItem> descFields = GetSummaryDescFields(loginUser, summaryReport);
            List <CalculatedClauseItem>  calcFields = GetSummaryCalcFields(loginUser, summaryReport);

            builder.Append("WITH x AS (");
            bool flag = true;

            foreach (DescriptiveClauseItem descField in descFields)
            {
                if (flag)
                {
                    builder.Append(string.Format(" SELECT {0} AS [{1}]", descField.Field, descField.Alias));
                }
                else
                {
                    builder.Append(string.Format(", {0} AS [{1}]", descField.Field, descField.Alias));
                }
                flag = false;
            }

            foreach (CalculatedClauseItem calcField in calcFields)
            {
                builder.Append(string.Format(", {0} AS [{1}]", calcField.Field, calcField.Alias));
            }

            // from + where clause
            builder.Append(" " + sub.BaseQuery);
            ReportTable mainTable = tables.FindByReportTableID(sub.ReportCategoryTableID);

            _organizationIDFieldName = mainTable.OrganizationIDFieldName;

            builder.Append(" WHERE (" + mainTable.TableName + "." + mainTable.OrganizationIDFieldName + " = @OrganizationID)");
            //add user rights where needed
            _userRights.UseTicketRights((int)summaryReport.Subcategory, tables, command, builder);
            if (isSchemaOnly)
            {
                builder.Append(" AND (0=1)");
            }

            // filters
            if (!isSchemaOnly)
            {
                Report.GetWhereClause(loginUser, command, builder, summaryReport.Filters);
                if (useUserFilter == true && reportID != null)
                {
                    Report report = Reports.GetReport(loginUser, (int)reportID, loginUser.UserID);
                    if (report != null && report.Row["Settings"] != DBNull.Value)
                    {
                        try
                        {
                            UserTabularSettings userFilters = JsonConvert.DeserializeObject <UserTabularSettings>((string)report.Row["Settings"]);
                            if (userFilters != null)
                            {
                                Report.GetWhereClause(loginUser, command, builder, userFilters.Filters);
                            }
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogs.LogException(loginUser, ex, "Summary SQL - User filters");
                        }
                    }
                }
            }
            flag = true;

            builder.Append(")"); // end with

            flag = true;
            foreach (DescriptiveClauseItem descField in descFields)
            {
                if (flag)
                {
                    builder.Append(string.Format(" SELECT [{0}]", descField.Alias));
                }
                else
                {
                    builder.Append(string.Format(", [{0}]", descField.Alias));
                }
                flag = false;
            }

            foreach (CalculatedClauseItem calcField in calcFields)
            {
                builder.Append(string.Format(", {0} AS [{1}]", calcField.AggField, calcField.Alias));
            }

            builder.Append(" FROM x ");

            // group by
            flag = true;
            foreach (DescriptiveClauseItem descField in descFields)
            {
                if (flag)
                {
                    builder.Append(string.Format(" GROUP BY [{0}]", descField.Alias));
                }
                else
                {
                    builder.Append(string.Format(", [{0}]", descField.Alias));
                }

                flag = false;
            }

            // having
            flag = true;
            foreach (CalculatedClauseItem calcField in calcFields)
            {
                if (calcField.Comparator == null)
                {
                    continue;
                }
                if (flag)
                {
                    builder.Append(string.Format(" HAVING {0}", calcField.Comparator));
                }
                else
                {
                    builder.Append(string.Format(" AND {0}", calcField.Comparator));
                }
                flag = false;
            }

            if (useDefaultOrderBy)
            {
                // order by

                /* flag = true;
                 * foreach (DescriptiveClauseItem descField in descFields)
                 * {
                 * if (flag)
                 *   builder.Append(string.Format(" ORDER BY [{0}]", descField.Alias));
                 * else
                 *   builder.Append(string.Format(", [{0}]", descField.Alias));
                 *
                 * flag = false;
                 * }*/

                // order by
                for (int i = descFields.Count - 1; i > -1; i--)
                {
                    if (i == descFields.Count - 1)
                    {
                        builder.Append(string.Format(" ORDER BY [{0}]", descFields[i].Alias));
                    }
                    else
                    {
                        builder.Append(string.Format(", [{0}]", descFields[i].Alias));
                    }
                }
            }
            command.CommandText = builder.ToString();
        }
Exemplo n.º 30
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.AddHeader("Expires", "-1");
            context.Response.AddHeader("Pragma", "no-cache");

            if (TSAuthentication.Ticket == null)
            {
                context.Response.ContentType = "text/plain";
                context.Response.StatusCode  = (int)HttpStatusCode.Forbidden;
                context.Response.ClearContent();
                context.Response.End();
                return;
            }

            TsChatUpdate update = new TsChatUpdate();

            using (Stream receiveStream = context.Request.InputStream)
            {
                using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    string  requestContent = readStream.ReadToEnd();
                    JObject args           = JObject.Parse(requestContent);

                    int lastChatRequestID = int.Parse(args["lastChatRequestID"].ToString());;
                    int lastChatMessageID = int.Parse(args["lastChatMessageID"].ToString());;

                    try
                    {
                        User user = Users.GetUser(LoginUser.Anonymous, TSAuthentication.UserID);

                        if (user == null)
                        {
                            context.Response.ContentType = "text/plain";
                            context.Response.StatusCode  = (int)HttpStatusCode.Forbidden;
                            context.Response.ClearContent();
                            context.Response.End();
                            return;
                        }

                        user.UpdatePing();

                        LoginUser loginUser = new LoginUser(user.UserID, user.OrganizationID, null);

                        List <GrowlMessage> chatMessageGrowl = new List <GrowlMessage>();
                        List <GrowlMessage> chatRequestGrowl = new List <GrowlMessage>();

                        update.LastChatRequestID = lastChatRequestID;
                        update.LastChatMessageID = lastChatMessageID;
                        update.ChatMessageCount  = 0;
                        update.ChatRequestCount  = 0;

                        if (user.IsChatUser && ChatUserSettings.GetSetting(loginUser, user.UserID).IsAvailable)
                        {
                            ChatMessages chatMessages = new ChatMessages(loginUser);
                            update.ChatMessageCount = chatMessages.GetUnreadMessageCount(loginUser.UserID, ChatParticipantType.User);
                            update.ChatRequestCount = user.IsChatUser ? ChatRequests.GetWaitingRequestCount(loginUser, loginUser.UserID, loginUser.OrganizationID) : 0;

                            if (lastChatMessageID < 0)
                            {
                                update.LastChatMessageID = ChatMessages.GetLastMessageID(loginUser);
                            }
                            chatMessages.LoadUnpreviewedMessages(loginUser.UserID, update.LastChatMessageID);

                            foreach (ChatMessage chatMessage in chatMessages)
                            {
                                chatMessageGrowl.Add(new GrowlMessage(chatMessage.Message, chatMessage.PosterName, "ui-state-active"));
                                update.LastChatMessageID = chatMessage.ChatMessageID;
                            }

                            ChatRequests requests = new ChatRequests(loginUser);
                            requests.LoadNewWaitingRequests(loginUser.UserID, loginUser.OrganizationID, lastChatRequestID);

                            foreach (ChatRequest chatRequest in requests)
                            {
                                chatRequestGrowl.Add(new GrowlMessage(string.Format("{0} {1} is requesting a chat!", chatRequest.Row["FirstName"].ToString(), chatRequest.Row["LastName"].ToString()), "Chat Request", "ui-state-error"));
                                update.LastChatRequestID = chatRequest.ChatRequestID;
                            }
                        }
                        update.NewChatMessages = chatMessageGrowl.ToArray();
                        update.NewChatRequests = chatRequestGrowl.ToArray();
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogs.LogException(LoginUser.Anonymous, ex, "Main Chat Upate");
                    }
                }
            }
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(update));
        }
Exemplo n.º 31
0
        private void QueueEmail(ScheduledReport scheduledReport)
        {
            scheduledReport.IsSuccessful = false;
            Log(string.Format("Scheduled Report Id: {0}, Report Id: {1}, Organization {2}", scheduledReport.Id.ToString(), scheduledReport.ReportId, scheduledReport.OrganizationId));
            Log(string.Format("Set to start on: {0}", scheduledReport.NextRun), LogType.Public);

            try
            {
                LoginUser scheduledReportCreator = new LoginUser(scheduledReport.CreatorId, scheduledReport.OrganizationId);
                Report    report = Reports.GetReport(scheduledReportCreator, scheduledReport.ReportId, scheduledReport.CreatorId);
                Log(string.Format("Generating {0} Report", report.ReportDefType.ToString()), LogType.Both);

                string reportAttachmentFile = string.Empty;

                if (report.ReportDefType == ReportType.Chart)
                {
                    reportAttachmentFile = GetReportChartFile(scheduledReportCreator, scheduledReport, report);
                }
                else
                {
                    reportAttachmentFile = GetReportDataToFile(scheduledReportCreator, report, scheduledReport, "", false, true, Logs);
                }

                if (!string.IsNullOrEmpty(reportAttachmentFile))
                {
                    if (report.ReportDefType != ReportType.Chart)
                    {
                        try
                        {
                            float fileSizeMB = 0;

                            if (File.Exists(reportAttachmentFile))
                            {
                                long fileSizeBytes = new FileInfo(reportAttachmentFile).Length;
                                fileSizeMB = (fileSizeBytes / 1024f) / 1024f;
                            }

                            //If the report is 2M or less, don't zip it.  If over 2M, zip it.
                            if (fileSizeMB > 2)
                            {
                                string zipFileName = reportAttachmentFile.Replace(".csv", ".zip");

                                if (File.Exists(zipFileName))
                                {
                                    try
                                    {
                                        File.Delete(zipFileName);
                                    }
                                    catch (IOException ioEx)
                                    {
                                        DateTime zipFileNamesuffix = scheduledReport.NextRun != null ? (DateTime)scheduledReport.NextRun : DateTime.UtcNow;
                                        zipFileName = zipFileName.Replace(".zip", string.Format("_{0}.zip", zipFileNamesuffix.ToString("yyyyMMddHHmm")));
                                        Log("Previous zip file could not be deleted. Naming the new one: ");
                                        Log(ioEx.Message + Environment.NewLine + ioEx.StackTrace);
                                    }
                                }

                                using (ZipArchive zip = ZipFile.Open(zipFileName, ZipArchiveMode.Create))
                                {
                                    zip.CreateEntryFromFile(reportAttachmentFile, Path.GetFileName(reportAttachmentFile));
                                }

                                if (File.Exists(zipFileName))
                                {
                                    Log("CSV File zipped", LogType.Both);

                                    try
                                    {
                                        File.Delete(reportAttachmentFile);
                                    }
                                    catch (IOException ioEx)
                                    {
                                        Log("CSV file could not be deleted.");
                                        Log(ioEx.Message + Environment.NewLine + ioEx.StackTrace);
                                    }

                                    reportAttachmentFile = zipFileName;
                                }
                                else
                                {
                                    Log("CSV zipped file was not found!");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("Error when zipping the CSV file.");
                            Log(ex.Message + Environment.NewLine + ex.StackTrace);
                        }
                    }

                    Log(string.Format("Report generated and file attachment created: {0}", Path.GetFileName(reportAttachmentFile)));

                    Organization  organization        = Organizations.GetOrganization(scheduledReportCreator, scheduledReportCreator.OrganizationID);
                    MailMessage   message             = EmailTemplates.GetScheduledReport(LoginUser, scheduledReport);
                    List <string> invalidEmailAddress = new List <string>();
                    scheduledReport.SetRecipientsAndAttachment(message, organization, ref invalidEmailAddress);

                    Log("Email message created", LogType.Public);
                    Log(string.Format("Email Recipients: {0}", string.Join(",", message.To.Select(p => p.Address).ToArray())), LogType.Both);

                    if (invalidEmailAddress.Any())
                    {
                        Log(string.Format("Invalid Email Recipients, they were excluded: {0}", string.Join(",", invalidEmailAddress.ToArray())), LogType.Both);
                    }

                    if (_isDebug == true)
                    {
                        string debugWhiteList = Settings.ReadString("Debug Email White List", "");
                        string debugDomains   = Settings.ReadString("Debug Email Domains", "");
                        string debugAddresses = Settings.ReadString("Debug Email Address", "");

                        if (!string.IsNullOrWhiteSpace(debugWhiteList))
                        {
                            Logs.WriteEvent("DEBUG Whitelist: " + debugWhiteList);
                            string[]           addresses     = debugWhiteList.Replace(';', ',').Split(',');
                            List <MailAddress> mailAddresses = new List <MailAddress>();

                            foreach (MailAddress mailAddress in message.To)
                            {
                                foreach (string address in addresses)
                                {
                                    if (mailAddress.Address.ToLower().IndexOf(address.ToLower()) > -1)
                                    {
                                        mailAddresses.Add(mailAddress);
                                    }
                                }
                            }

                            message.To.Clear();

                            foreach (MailAddress mailAddress in mailAddresses)
                            {
                                message.To.Add(mailAddress);
                            }
                        }
                        else if (!string.IsNullOrWhiteSpace(debugDomains))
                        {
                            Logs.WriteEvent("DEBUG Domains: " + debugDomains);
                            string[]           domains       = debugDomains.Replace(';', ',').Split(',');
                            List <MailAddress> mailAddresses = new List <MailAddress>();

                            foreach (MailAddress mailAddress in message.To)
                            {
                                foreach (string domain in domains)
                                {
                                    if (mailAddress.Address.ToLower().IndexOf(domain.ToLower()) > -1)
                                    {
                                        mailAddresses.Add(mailAddress);
                                    }
                                }
                            }

                            message.To.Clear();

                            foreach (MailAddress mailAddress in mailAddresses)
                            {
                                message.To.Add(mailAddress);
                            }
                        }
                        else if (!string.IsNullOrWhiteSpace(debugAddresses))
                        {
                            Logs.WriteEvent("DEBUG Addresses: " + debugAddresses);
                            message.To.Clear();
                            message.To.Add(debugAddresses.Replace(';', ','));
                        }
                        else
                        {
                            Logs.WriteEvent("NO DEBUG FILTERS SET");
                            return;
                        }

                        if (message.To.Count < 1)
                        {
                            Logs.WriteEvent("No Debug Address specified.");
                            return;
                        }

                        message.Subject = string.Format("[{0}] {1}", Settings.ReadString("Debug Email Subject", "TEST MODE"), message.Subject);
                    }

                    Log("Queueing email(s)", LogType.Public);
                    AddMessage(scheduledReport.OrganizationId, string.Format("Scheduled Report Sent [{0}]", scheduledReport.Id), message, null, new string[] { reportAttachmentFile });
                    scheduledReport.IsSuccessful = true;
                }
                else
                {
                    Log("Report could not be generated and emailed, please contact TeamSupport", LogType.Public);
                }

                if ((ScheduledReportFrequency)scheduledReport.RecurrencyId == ScheduledReportFrequency.Once)
                {
                    scheduledReport.NextRun = null;
                }
                else
                {
                    scheduledReport.SetNextRun(true);
                }

                scheduledReport.RunCount      = scheduledReport.RunCount != null ? (short)(scheduledReport.RunCount + 1) : (short)1;
                scheduledReport.LastRun       = DateTime.UtcNow;
                scheduledReport.LockProcessId = null;
                scheduledReport.Collection.Save();
                Log(string.Format("Set next run to: {0}", scheduledReport.NextRun == null ? "Never" : scheduledReport.NextRun.ToString()), LogType.Both);
            }
            catch (Exception ex)
            {
                Logs.WriteException(ex);
                ExceptionLogs.LogException(LoginUser, ex, _threadPosition.ToString() + " - Report Sender", scheduledReport.Row);
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Update the Ticket related fields that live in their own table.
        /// </summary>
        /// <param name="command">Command received in the request to read and process the data in the request body.</param>
        /// <param name="ticketId">TicketId to update its record.</param>
        private static void UpdateFieldsOfSeparateTable(RestCommand command, Ticket ticket, bool isCustomerTicket = false)
        {
            try
            {
                //Add as necessary to the list and then to the switch-case below for the work to update it.
                List <string> fields = new List <string>()
                {
                    "jirakey", "tags"
                };

                foreach (string field in fields.Select(p => p.ToLower()).ToList())
                {
                    XmlNode node = GetNode(command, field);

                    if (node != null)
                    {
                        switch (field)
                        {
                        case "jirakey":
                            string           jiraKey          = node.InnerText;
                            TicketLinkToJira ticketLinkToJira = new TicketLinkToJira(command.LoginUser);
                            ticketLinkToJira.LoadByTicketID(ticket.TicketID);
                            int?crmLinkId = null;

                            //Next line and 2 If statements are the same as in \webapp\app_code\ticketservice.cs SetSyncWithJira(). Might need to consider making a common funcion for both
                            crmLinkId = CRMLinkTable.GetIdBy(ticket.OrganizationID, IntegrationType.Jira.ToString().ToLower(), ticket.ProductID, command.LoginUser);

                            //If product is not associated to an instance then get the 'default' instance
                            if (crmLinkId == null || crmLinkId <= 0)
                            {
                                CRMLinkTable crmlink = new CRMLinkTable(command.LoginUser);
                                crmlink.LoadByOrganizationID(ticket.OrganizationID);

                                crmLinkId = crmlink.Where(p => p.InstanceName == "Default" &&
                                                          p.CRMType.ToLower() == IntegrationType.Jira.ToString().ToLower())
                                            .Select(p => p.CRMLinkID).FirstOrDefault();
                            }

                            if (ticketLinkToJira != null && ticketLinkToJira.Any())
                            {
                                string oldJiraKey = ticketLinkToJira[0].JiraKey;
                                ticketLinkToJira[0].JiraKey   = jiraKey.ToLower() == "newjiraissue" ? null : jiraKey;
                                ticketLinkToJira[0].CrmLinkID = crmLinkId;
                                ticketLinkToJira.Save();
                                ActionLogs.AddActionLog(command.LoginUser, ActionLogType.Update, ReferenceType.Tickets, ticket.TicketID, string.Format("Changed JiraKey from '{0}' to '{1}'.", oldJiraKey, jiraKey));
                            }
                            else
                            {
                                TicketLinkToJiraItem newJiraLink = ticketLinkToJira.AddNewTicketLinkToJiraItem();
                                newJiraLink.TicketID     = ticket.TicketID;
                                newJiraLink.SyncWithJira = true;
                                newJiraLink.JiraID       = null;
                                newJiraLink.JiraKey      = jiraKey.ToLower() == "newjiraissue" ? null : jiraKey;
                                newJiraLink.JiraLinkURL  = null;
                                newJiraLink.JiraStatus   = null;
                                newJiraLink.CreatorID    = command.LoginUser.UserID;
                                newJiraLink.CrmLinkID    = crmLinkId;

                                if (newJiraLink.CrmLinkID != null && newJiraLink.CrmLinkID > 0)
                                {
                                    newJiraLink.Collection.Save();
                                    ActionLogs.AddActionLog(command.LoginUser, ActionLogType.Update, ReferenceType.Tickets, ticket.TicketID, string.Format("Linked to JiraKey '{0}'.", jiraKey));
                                }
                            }
                            break;

                        case "tags":
                            TagLinks currentTagLinks = new TagLinks(command.LoginUser);
                            currentTagLinks.LoadByReference(ReferenceType.Tickets, ticket.TicketID);
                            XmlNodeList nodeList = node.ChildNodes;
                            List <int>  newTags  = new List <int>();

                            foreach (XmlNode tagNode in nodeList)
                            {
                                string tagValue = tagNode["Value"].InnerText;

                                Tag newTag = Tags.GetTag(command.LoginUser, tagValue);

                                if (newTag == null)
                                {
                                    Tags tag = new Tags(command.LoginUser);
                                    newTag = tag.AddNewTag();
                                    newTag.OrganizationID = isCustomerTicket ? command.Organization.ParentID ?? command.Organization.OrganizationID : command.Organization.OrganizationID;
                                    newTag.Value          = tagValue;
                                    tag.Save();
                                }

                                newTags.Add(newTag.TagID);
                            }

                            foreach (int tag in newTags)
                            {
                                TagLink newTagLink = currentTagLinks.Where(p => p.TagID == tag && p.RefID == ticket.TicketID).SingleOrDefault();
                                if (newTagLink == null)
                                {
                                    TagLinks tagLink = new TagLinks(command.LoginUser);
                                    newTagLink         = tagLink.AddNewTagLink();
                                    newTagLink.TagID   = tag;
                                    newTagLink.RefType = ReferenceType.Tickets;
                                    newTagLink.RefID   = ticket.TicketID;
                                    tagLink.Save();
                                }
                            }

                            List <TagLink> deleteTagLinks = currentTagLinks.Where(p => !newTags.Contains(p.TagID)).ToList();

                            foreach (TagLink deleteTagLink in deleteTagLinks)
                            {
                                deleteTagLink.Delete();
                                deleteTagLink.Collection.Save();
                            }

                            break;

                        default:
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(command.LoginUser, ex, "API", string.Format("OrgID: {0}{1}Verb: {2}{1}Url: {3}{1}Body: {4}", command.Organization.OrganizationID, Environment.NewLine, command.Method, command.Method, command.Data));
            }
        }
Exemplo n.º 33
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.AddHeader("Expires", "-1");
            context.Response.AddHeader("Pragma", "no-cache");

            if (TSAuthentication.Ticket == null)
            {
                context.Response.ContentType = "text/plain";
                context.Response.StatusCode  = (int)HttpStatusCode.Forbidden;
                context.Response.ClearContent();
                context.Response.End();
                return;
            }

            string sessionID = context.Request.Url.Segments[context.Request.Url.Segments.Length - 1];

            TsMainPageUpdate update = new TsMainPageUpdate();

            try
            {
                update.IsDebug   = TSAuthentication.OrganizationID == 1078 || TSAuthentication.IsBackdoor;
                update.IsExpired = false;

                using (SqlConnection connection = new SqlConnection(LoginUser.Anonymous.ConnectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand();
                    command.Connection  = connection;
                    command.CommandText = "SELECT EnforceSingleSession, SessionID, IsActive, MarkDeleted FROM Users WHERE UserID = @UserID";
                    command.Parameters.AddWithValue("UserID", TSAuthentication.UserID);
                    SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
                    if (reader.Read())
                    {
                        if (!(bool)reader[2] || (bool)reader[3])
                        {
                            update.IsExpired = true;
                        }
                        else if ((bool)reader[0] && reader[1] != DBNull.Value)
                        {
                            if (sessionID != null && sessionID.ToLower() != reader[1].ToString().ToLower() && !TSAuthentication.IsBackdoor)
                            {
                                update.IsExpired = true;
                            }
                        }
                    }
                    reader.Close();
                }

                update.RefreshID           = int.Parse(SystemSettings.ReadString(LoginUser.Anonymous, "RefreshID", "-1"));
                update.ExpireTime          = TSAuthentication.Ticket.Expiration.ToShortTimeString();
                update.Version             = GetVersion(context);
                update.MyUnreadTicketCount = Tickets.GetMyOpenUnreadTicketCount(TSAuthentication.GetLoginUser(), TSAuthentication.UserID);
            }
            catch (Exception ex)
            {
                ex.Data["SessionID"] = sessionID;
                ExceptionLogs.LogException(LoginUser.Anonymous, ex, "GetUserStatusUpdate");
            }


            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(update));
        }
    protected override void OnInit(EventArgs e)
    {
        CachePage = true;

        base.OnInit(e);


        gridReport.GroupingSettings.CaseSensitive = false;

        _report = null;
        try
        {
            _reportID = int.Parse(Request["ReportID"]);
            if (_reportID < 0)
            {
                throw new Exception("Invalid ReportID");
            }
            _report = (Report)Reports.GetReport(UserSession.LoginUser, _reportID);
            if (_report == null)
            {
                throw new Exception("Invalid Report");
            }
            if (_report.OrganizationID != null && UserSession.LoginUser.OrganizationID != 1 && UserSession.LoginUser.OrganizationID != 1078)
            {
                if (_report.OrganizationID != UserSession.LoginUser.OrganizationID)
                {
                    _report = null;
                    throw new Exception("Invalid Report");
                }
            }
        }
        catch (Exception ex)
        {
            ExceptionLogs.LogException(UserSession.LoginUser, ex, "ReportResults");
            Response.Write("There was an error retrieving your report.");
            Response.End();
            return;
        }
        _isCustom = _report.ReportSubcategoryID != null;

        fieldReportID.Value = _reportID.ToString();

        if (!IsPostBack)
        {
            if (_isCustom)
            {
                filterControl.ReportSubcategoryID = (int)_report.ReportSubcategoryID;
                filterControl.ReportID            = _reportID;
                int h = Settings.UserDB.ReadInt("ReportFilterHeight_" + _reportID.ToString(), 175);
                if (h > 300)
                {
                    h = 300;
                }
                paneFilters.Height = new Unit(h, UnitType.Pixel);
            }
            else
            {
                //paneFilters.Visible = false;
                paneFilters.Height = new Unit(1, UnitType.Pixel);
                barFilters.Visible = false;
            }


            try
            {
                CreateColumns(_report);
                LoadReportSettings();
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(UserSession.LoginUser, ex, "Reports");
            }
        }
    }