Example #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sessionTokenId"></param>
        /// <param name="url"></param>
        /// <param name="marginLeft"></param>
        /// <param name="marginTop"></param>
        /// <returns></returns>
        int IPrintServiceV1.GetNumberOfPages(string sessionTokenId, string url, int marginLeft, int marginTop)
        {
            string extension = string.Empty;

            extension = GetExtension(url);
            extension = extension.ToLower(CultureInfo.InvariantCulture);
            int numberOfPages = 0;

            if (marginLeft < 10000 && marginTop < 10000)
            {
                try
                {
                    bool isQualified = IsQualifiedUrl(url.ToString());
                    if (isQualified)
                    {
                        numberOfPages = GetNumberOfPages(url, extension, marginLeft, marginTop);
                    }
                }
                catch (WebException webEx)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, webEx.StackTrace,
                                         webEx.Message + webEx.StackTrace + HttpUtility.UrlEncode(url.ToString()));
                }
                catch (Exception ex)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace,
                                         ex.Message + ex.StackTrace + HttpUtility.UrlEncode(url.ToString()));
                }
            }
            return(numberOfPages);
        }
Example #2
0
 /// <summary>
 /// Save Copyright Configuration to Database
 /// </summary>
 /// <param name="copyright"></param>
 /// <returns></returns>
 public static bool SaveDbCopyrightConfig(Models.Copyright copyright)
 {
     try
     {
         Database     db         = DatabaseFactory.CreateDatabase(DatabaseConnectionString);
         DbConnection connection = db.CreateConnection();
         DbCommand    dbCommand  = db.GetStoredProcCommand(StoreSaveCopyrightConfiguration);
         dbCommand.Connection = connection;
         dbCommand.Connection.Open();
         dbCommand.Parameters.Add(new SqlParameter("projectName", copyright.ProjectName));
         dbCommand.Parameters.Add(new SqlParameter("activeStatus", copyright.ActiveStatus));
         dbCommand.Parameters.Add(new SqlParameter("copyRightText", copyright.CopyrightText));
         dbCommand.Parameters.Add(new SqlParameter("repositoryURL", copyright.RepositoryUrl));
         dbCommand.Parameters.Add(new SqlParameter("controlType", copyright.ControlType));
         dbCommand.Parameters.Add(new SqlParameter("emailreport", copyright.Emailreport == null ? "" : copyright.Emailreport));
         dbCommand.ExecuteNonQuery();
         return(true);
     }
     catch (Exception ex)
     {
         WriteLogFile(ex.Message + ex.StackTrace);
         LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
         WriteLogFile(ex.Message + ex.StackTrace);
         return(false);
     }
 }
Example #3
0
        /// <summary>
        /// Load all active copyright configuration
        /// </summary>
        /// <returns></returns>
        public static List <Models.Copyright> LoadActiveRepo()
        {
            List <Models.Copyright> lstCopyRight = new List <Models.Copyright>();

            try
            {
                Database    db        = DatabaseFactory.CreateDatabase(DatabaseConnectionString);
                DbCommand   dbCommand = db.GetStoredProcCommand(StoreLoadActiveRepo);
                IDataReader dr        = db.ExecuteReader(dbCommand);
                while (dr.Read())
                {
                    Models.Copyright copyright = new Models.Copyright();
                    //copyright.ProjectName = dr[ContsProjectName].ToString();
                    //copyright.ActiveStatus = Convert.ToBoolean(dr[ContsActiveStatus]);
                    copyright.CopyrightText = dr[ContsCopyrightText].ToString();
                    copyright.RepositoryUrl = dr[ContsRepositoryUrl].ToString();
                    lstCopyRight.Add(copyright);
                }
            }
            catch (Exception ex)
            {
                LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
                throw ex;
            }
            return(lstCopyRight);
        }
Example #4
0
 /// <summary>
 /// Load Copyright Configuration by specific ProjectId from Database
 /// </summary>
 /// <param name="projectName"></param>
 /// <returns></returns>
 public static Models.Copyright LoadDbCopyrightConfigByProjectId(string projectName)
 {
     Models.Copyright copyright = null;
     try
     {
         Database  db        = DatabaseFactory.CreateDatabase(DatabaseConnectionString);
         DbCommand dbCommand = db.GetStoredProcCommand(StoreLoadCopyrightConfigByProjectId);
         dbCommand.Parameters.Add(new SqlParameter("projectName", projectName));
         IDataReader dr = db.ExecuteReader(dbCommand);
         while (dr.Read())
         {
             copyright               = new Models.Copyright();
             copyright.ProjectName   = dr[ContsProjectName].ToString();
             copyright.ActiveStatus  = Convert.ToBoolean(dr[ContsActiveStatus]);
             copyright.CopyrightText = dr[ContsCopyrightText].ToString();
             copyright.RepositoryUrl = dr[ContsRepositoryUrl].ToString();
             copyright.ControlType   = dr[ContsControlType].ToString();
             copyright.Emailreport   = dr[ContsEmailReport].ToString();
         }
     }
     catch (Exception ex)
     {
         LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
         WriteLogFile(ex.Message + ex.StackTrace);
         return(null);
     }
     return(copyright);
 }
Example #5
0
        private static List <Models.Copyright> GetAllCopyright()
        {
            List <Models.Copyright> lstCopyright = new List <Models.Copyright>();

            try
            {
                SessionTokenClient.SessionTokenServiceV2Client sessionToken =
                    new SessionTokenServiceV2Client("BasicHttpBinding_ISessionTokenServiceV2");
                string username        = System.Configuration.ConfigurationManager.AppSettings["SessionUserName"];
                string password        = System.Configuration.ConfigurationManager.AppSettings["SessionPassword"];
                string bucketnamespace = System.Configuration.ConfigurationManager.AppSettings["BucketNameSpace"];
                string bucketpassword  = System.Configuration.ConfigurationManager.AppSettings["BucketPassword"];
                string sessionTokenID  = GetSessionTokenGuidId(username, password);
                NifDBClient.KeyBaseServiceV1Client NifDB =
                    new KeyBaseServiceV1Client("BasicHttpBinding_IKeyBaseServiceV1");

                string xml =
                    (string)NifDB.GetString(sessionTokenID, bucketnamespace, bucketpassword, ContsNifDbKey);
                if (xml != null)
                {
                    lstCopyright = DeserializeObject(xml);
                }
            }
            catch (Exception ex)
            {
                LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
                return(null);
            }
            return(lstCopyright);
        }
Example #6
0
        /// <summary>
        /// Save Copyright Configuration
        /// </summary>
        /// <param name="copyright"></param>
        /// <returns></returns>
        public static int SaveCopyrightConfiguration(Models.Copyright copyright)
        {
            int res = 0;

            try
            {
                //check exist data with CopyrightServiceKey
                List <Models.Copyright> lstCopyright = GetAllCopyright();

                if (lstCopyright == null)
                {
                    lstCopyright = new List <Models.Copyright>();
                }
                int index = lstCopyright.FindIndex(p => p.ProjectName.ToLower() == copyright.ProjectName.ToLower());
                if (index < 0)
                {
                    lstCopyright.Add(copyright);
                }
                else
                {
                    lstCopyright[index] = copyright;
                }

                string result = SaveCopyrightToNifDb(lstCopyright);
            }
            catch (Exception ex)
            {
                LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
                throw ex;
            }
            return(res);
        }
        /// <summary>
        /// Application_Error event.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Arguments</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception baseException = Server.GetLastError().GetBaseException();

            // Log the exception
            LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name,
                                 Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                 Environment.MachineName,
                                 baseException.StackTrace,
                                 baseException.Message + baseException.StackTrace);
        }
Example #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string convertUri = "";
                convertUri = context.Request.QueryString.ToString();
                string temp1 = HttpUtility.UrlDecode(convertUri.Substring(4, convertUri.IndexOf(".html") + 1));
                string temp2 = convertUri.Substring(convertUri.IndexOf(".html") + 5);
                convertUri = temp1 + temp2;
                convertUri = HttpUtility.UrlDecode(convertUri);
                string domain           = new Uri(convertUri).GetLeftPart(UriPartial.Authority);
                string query            = new Uri(convertUri).Query;
                string convertUriDomain = domain;
                if (query.Length > 0)
                {
                    convertUriDomain = convertUri.Replace(
                        new Uri(convertUri).Query == null ? "" : new Uri(convertUri).Query, "");
                }
                else
                {
                    convertUriDomain = convertUri;
                }
                if (convertUriDomain.Substring(convertUriDomain.Length - 1) == "/")
                {
                    convertUriDomain = convertUriDomain.Substring(0, convertUriDomain.Length - 1);
                }


                string respone = GetHtmlText(convertUri);

                respone = RegexReplace(respone, "href=\"(.)+([.]css)(.)+(^<)?(/>)", "href=\"", domain, domain);

                respone = RegexReplace(respone, "href=\"(.)+<[^.css]+?>", "href=\"", domain, convertUriDomain);

                respone = RegexReplace(respone, "href='(.)+<[^.css]+?>'", "href='", domain, convertUriDomain);

                respone = RegexReplace(respone, "src=\"(.)+\"", "src=\"", domain, convertUriDomain);

                respone = RegexReplace(respone, "src='(.)+'", "src='", domain, convertUriDomain);

                respone = RegexReplace(respone, "url(.)+\"", "url(", domain, convertUriDomain);

                respone = ReplaceIframe(respone);

                context.Response.ContentType = "text/HTML";
                context.Response.Write(respone);
            }
            catch (Exception ex)
            {
                LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
            }
        }
Example #9
0
 /// <summary>
 /// This method will check from data for all active repository and call force copyright to all ones
 /// </summary>
 /// <returns></returns>
 public ActionResult ForceAllActiveRepo()
 {
     try
     {
         Thread thread = new Thread(StartActiveRepo);
         thread.Start();
     }
     catch (Exception ex)
     {
         LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
     }
     return(View());
 }
        /// <summary>
        /// Check if an url is qualified to generate a pdf or images
        /// </summary>
        /// <param name="url">Input url</param>
        /// <returns>Returns a boolean value to indicate if an url is qulified or not. True is qualified, False is not qualified.</returns>
        public bool IsQualifiedUrl(string url)
        {
            bool isContained = false;
            // Get the qualified domain from web.config
            string domainFiltering = System.Web.Configuration.WebConfigurationManager.AppSettings[constFilterdDomain];

            try
            {
                //string domainFiltering = RoleEnvironment.GetConfigurationSettingValue(constFilterdDomain);

                // Split the string into an array
                string[] filteredDomains = domainFiltering.Split(new char[] { ',' });

                // Loop the array of domain to check if the input url contains one element in the filtered domains
                // if the input url contains one element in the filtered domains, that is the url has been qualified to generate a pdf file
                // after that we will break the loop and return the value.
                // else we will return false value. That means the url is not qualified to generate a pdf file.
                foreach (string domain in filteredDomains)
                {
                    int indexOfStar = domain.IndexOf("*");

                    string subdomain = string.Empty;
                    if (indexOfStar >= 0)
                    {
                        subdomain = domain.Substring(indexOfStar + 2);
                    }
                    else
                    {
                        subdomain = domain;
                    }
                    if (url.Contains(subdomain))
                    {
                        isContained = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
            }

            return(isContained);
        }
Example #11
0
        private static string GetSessionTokenGuidId(string username, string password)
        {
            string id = "";

            try
            {
                string sessionUrl = System.Configuration.ConfigurationManager.AppSettings["SessionTokenAddress"];
                string requestUrl = sessionUrl + "/POX/ISessionTokenServiceV2/CreateSessionToken?userName="******"&password="******"<a:AuthorizedSessionToken>"),
                                                          xmlDocument.ToString().IndexOf("</a:AuthorizedSessionToken>") -
                                                          xmlDocument.ToString().IndexOf("<a:AuthorizedSessionToken>")).
                         Replace("<a:AuthorizedSessionToken>", "");
                }
            }
            catch (Exception ex)
            {
                LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
                throw ex;
            }
            return(id);
        }
Example #12
0
 /// <summary>
 /// Load Copyright Configuration by specific ProjectId
 /// </summary>
 /// <param name="projectName"></param>
 /// <returns></returns>
 public static Models.Copyright LoadCopyrightConfigByProjectId(string projectName)
 {
     Models.Copyright copyright = null;
     try
     {
         //Get copyright data from NifDB
         List <Models.Copyright> lstCopyright = GetAllCopyright();
         if (lstCopyright != null && lstCopyright.Count > 0)
         {
             copyright = (from item in lstCopyright
                          where item.ProjectName.ToLower() == projectName.ToLower()
                          select item).First();
         }
     }
     catch (Exception ex)
     {
         LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
         return(null);
     }
     return(copyright);
 }
Example #13
0
        public ActionResult Index(Copyright.WebApplication.Models.Copyright copyRight, string btnForce, string btnSave, string ddlSourceType, string Emailreport)
        {
            CopyrightServiceV1Client copyrightService = new CopyrightServiceV1Client("BasicHttpBinding_ICopyrightServiceV1");

            try
            {
                copyRight.ControlType = ddlSourceType;
                if (!string.IsNullOrEmpty(btnSave))
                {
                    if (ModelState.IsValid)
                    {
                        if (copyRight.ControlType == "GIT")
                        {
                            if (copyrightService.IsExistRepository(copyRight.RepositoryUrl).Id == 1)//copyrightService.IsExistRepository(copyRight.RepositoryUrl)
                            {
                                Dal.CopyrightDb.SaveDbCopyrightConfig(copyRight);
                                return(JavaScript("SaveSuccessfullMsg();"));
                            }
                            else
                            {
                                copyrightService.SendEmailReport(Emailreport, "Unable to access the Git repository URL: " + copyRight.RepositoryUrl + "<br/>Please verify that the specified URL is accurate. ");
                                return(JavaScript("SaveUnSuccessfullMsg();"));
                            }
                        }
                        else
                        {
                            if (copyrightService.IsExistSourcePath(copyRight.RepositoryUrl))
                            {
                                Dal.CopyrightDb.SaveDbCopyrightConfig(copyRight);
                                return(JavaScript("SaveSuccessfullMsg();"));
                            }
                            else
                            {
                                copyrightService.SendEmailReport(Emailreport, "Unable to access the TFS Path: " + copyRight.RepositoryUrl + "<br/>Please verify that the specified path is accurate. ");
                                return(JavaScript("SaveUnSuccessfullMsg();"));
                            }
                        }
                    }
                }
                else if (!string.IsNullOrEmpty(btnForce))
                {
                    if (!copyrightService.IsProcessing(copyRight.RepositoryUrl))
                    {
                        ObjectResponseV1 response = new ObjectResponseV1();
                        bool             isExist  = false;
                        if (copyRight.ControlType == "GIT")
                        {
                            response = copyrightService.IsExistRepository(copyRight.RepositoryUrl);
                        }
                        else
                        {
                            isExist = copyrightService.IsExistSourcePath(copyRight.RepositoryUrl);
                        }
                        if (isExist || response.Id == 1)
                        {
                            if (copyRight.ControlType == "GIT")
                            {
                                RepoUrl       = copyRight.RepositoryUrl;
                                CopyrightText = copyRight.CopyrightText;
                                Thread thread = new Thread(unused => StartThread(copyRight.RepositoryUrl, copyRight.CopyrightText, Emailreport));
                                thread.Start();
                            }
                            else
                            {
                                RepoUrl       = copyRight.RepositoryUrl;
                                CopyrightText = copyRight.CopyrightText;
                                Thread thread = new Thread(unused => StartTfsThread(copyRight.ProjectName, copyRight.RepositoryUrl, copyRight.CopyrightText, Emailreport));
                                thread.Start();
                            }
                        }
                        else
                        {
                            if (copyRight.ControlType == "GIT")
                            {
                                copyrightService.SendEmailReport(Emailreport, "Unable to access the Git repository URL: " + copyRight.RepositoryUrl + "<br/>Please verify that the specified URL is accurate. ");
                            }
                            else
                            {
                                copyrightService.SendEmailReport(Emailreport, "Unable to access the TFS Path: " + copyRight.RepositoryUrl + "<br/>Please verify that the specified path is accurate. ");
                            }
                            return(JavaScript("ForceFailMsg('" + response.Description + "');"));
                        }
                    }
                    else
                    {
                        return(JavaScript("IsRunningMsg();"));
                    }
                    copyRight.ForceMessage = "Forcing";
                    return(JavaScript("window.location.reload();"));
                }
            }
            catch (Exception ex)
            {
                copyrightService.SendEmailReport(Emailreport, ex.Message + ex.StackTrace);
                LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
                return(JavaScript("ForceFailMsg('" + ex.Message + "');"));
            }
            return(View(copyRight));
        }
Example #14
0
        /// <summary>
        /// Button Export Image action
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonExportImage_Click(object sender, EventArgs e)
        {
            try
            {
                literalViewer.Text            = string.Empty;
                literalHttpStatusMessage.Text = string.Empty;
                StringBuilder imageText = new StringBuilder();

                string webservicePath = ConfigurationManager.AppSettings[printerUrl];

                Uri    requestURL = Request.Url;
                string original   = requestURL.OriginalString;

                string pathAndQuery = requestURL.PathAndQuery;
                original = original.Replace(pathAndQuery, string.Empty);

                string url = original + webservicePath;

                string strUrl     = textBoxUrl.Text;
                int    marginLeft = 0;
                if (!string.IsNullOrEmpty(textBoxMarginLeft.Text))
                {
                    marginLeft = Int32.Parse(textBoxMarginLeft.Text, CultureInfo.InvariantCulture);
                }
                int marginTop = 0;
                if (!string.IsNullOrEmpty(textBoxMarginTop.Text))
                {
                    marginTop = Int32.Parse(textBoxMarginTop.Text, CultureInfo.InvariantCulture);
                }
                string format = dropDownListFormat.SelectedValue;


                string requestUrl = string.Format(CultureInfo.InvariantCulture, "{0}/POX/IPrintServiceV1/GetNumberOfPages?sessionTokenId={1}&url={2}&marginLeft={3}&marginTop={4}", url, _dummySessionToken, HttpUtility.UrlEncode(strUrl), marginLeft, marginTop);

                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(new Uri(requestUrl));

                webrequest.Method = "GET";
                HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();

                    string xml = new StreamReader(stream).ReadToEnd();

                    if (!string.IsNullOrEmpty(xml))
                    {
                        XDocument xmlDocument = XDocument.Parse(xml);
                        RemoveAttributes(xmlDocument.Root);

                        Type[] extraTypes = new Type[1];
                        extraTypes[0] = typeof(byte[]);

                        string xmlString = xmlDocument.ToString();

                        xmlString = xmlString.Replace("ArrayOfanyType", "ArrayOfAnyType");

                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(int));
                        using (StringReader reader = new StringReader(xmlString))
                        {
                            int numberOfPages = (int)xmlSerializer.Deserialize(reader);
                            if (numberOfPages != 0)
                            {
                                for (int i = 1; i <= numberOfPages; i++)
                                {
                                    imageText.AppendLine("<img src='" +
                                                         string.Format(CultureInfo.InvariantCulture,
                                                                       "{0}/POX/IPrintServiceV1/ConvertUrlToImage?sessionTokenId={1}&url={2}&marginLeft={3}&marginTop={4}&format={5}&page={6}",
                                                                       url, _dummySessionToken, HttpUtility.UrlEncode(strUrl),
                                                                       marginLeft, marginTop, format, i) +
                                                         "'/><button onclick=\"OnPrint('" +
                                                         string.Format(CultureInfo.InvariantCulture,
                                                                       "{0}/POX/IPrintServiceV1/ConvertUrlToImage?sessionTokenId={1}&url={2}&marginLeft={3}&marginTop={4}&format={5}&page={6}",
                                                                       url, _dummySessionToken, HttpUtility.UrlEncode(strUrl),
                                                                       marginLeft, marginTop, format, i) +
                                                         "')\">Print</button><br/>");
                                }
                            }
                            literalHttpStatusMessage.Text = imageText.ToString();
                        }
                    }
                    else
                    {
                        literalHttpStatusMessage.Text = _errorMessage;
                    }
                }
                else
                {
                    literalHttpStatusMessage.Text = response.StatusDescription;
                }
            }
            catch (TimeoutException ex)
            {
                literalHttpStatusMessage.Text = ex.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
            }
            catch (FileNotFoundException fileNotFoundEx)
            {
                literalHttpStatusMessage.Text = fileNotFoundEx.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, fileNotFoundEx.StackTrace, fileNotFoundEx.Message + fileNotFoundEx.StackTrace);
            }
            catch (WebException webEx)
            {
                literalHttpStatusMessage.Text = webEx.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, webEx.StackTrace, webEx.Message + webEx.StackTrace);
            }
            catch (HttpException httpException)
            {
                literalHttpStatusMessage.Text = httpException.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, httpException.StackTrace, httpException.Message + httpException.StackTrace);
            }
            catch (UriFormatException uriFormatException)
            {
                literalHttpStatusMessage.Text = uriFormatException.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, uriFormatException.StackTrace, uriFormatException.Message + uriFormatException.StackTrace);
            }
        }
        /// <summary>
        /// ConvertURLToImage
        /// </summary>
        /// <param name="sessionTokenId">sessionTokenId</param>
        /// <param name="extension">extension</param>
        /// <param name="url">url</param>
        /// <param name="marginLeft">marginLeft</param>
        /// <param name="marginTop">marginTop</param>
        /// <param name="format">format</param>
        /// <param name="page">page</param>
        /// <returns></returns>
        public byte[] ConvertURLToImage(string sessionTokenId, string extension, string url, int marginLeft, int marginTop, string format, int page)
        {
            try
            {
                HttpContext httpContext = HttpContext.Current;
                string      domainName  = string.Format(CultureInfo.InvariantCulture, const_Domainformat,
                                                        httpContext.Request.Url.Scheme,
                                                        httpContext.Request.Url.Host,
                                                        httpContext.Request.Url.Port);

                MemoryStream memoryStream         = new MemoryStream();
                string       requestUrlForConvert = string.Format(ConfigurationManager.AppSettings[StaticConstants.Const_ConvertURLToImageFormat],
                                                                  domainName + ConfigurationManager.AppSettings[StaticConstants.Const_PrinterUrl],
                                                                  sessionTokenId,
                                                                  HttpUtility.UrlEncode(url),
                                                                  marginLeft,
                                                                  marginTop,
                                                                  format,
                                                                  page);
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(requestUrlForConvert);
                webrequest.Method = StaticConstants.Const_Get;
                HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        stream.CopyTo(memoryStream);
                    }
                }
                return(memoryStream.ToArray());
            }
            catch (UriFormatException uriFormatException)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name,
                                     Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                     Environment.MachineName,
                                     uriFormatException.StackTrace,
                                     HttpUtility.UrlEncode(url) + uriFormatException.Message + uriFormatException.StackTrace);
                return(null);
            }
            catch (WebException webException)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name,
                                     Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                     Environment.MachineName,
                                     webException.StackTrace,
                                     HttpUtility.UrlEncode(url) + webException.Message + webException.StackTrace);
                return(null);
            }
            catch (Exception ex)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name,
                                     Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                     Environment.MachineName,
                                     ex.StackTrace,
                                     HttpUtility.UrlEncode(url) + ex.Message + ex.StackTrace);
                return(null);
            }
        }
Example #16
0
        /// <summary>
        /// Button Export PDF Action
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonExportPdf_Click(object sender, EventArgs e)
        {
            try
            {
                literalViewer.Text            = string.Empty;
                literalHttpStatusMessage.Text = string.Empty;
                int marginLeft = 0;
                if (!string.IsNullOrEmpty(textBoxMarginLeft.Text))
                {
                    marginLeft = Int32.Parse(textBoxMarginLeft.Text, CultureInfo.InvariantCulture);
                }
                int marginTop = 0;
                if (!string.IsNullOrEmpty(textBoxMarginTop.Text))
                {
                    marginTop = Int32.Parse(textBoxMarginTop.Text, CultureInfo.InvariantCulture);
                }
                string webservicePath = ConfigurationManager.AppSettings[printerUrl];
                Uri    requestURL     = Request.Url;
                string original       = requestURL.OriginalString;

                string pathAndQuery = requestURL.PathAndQuery;
                original = original.Replace(pathAndQuery, string.Empty);

                string webserviceUrl = original + webservicePath;

                string          url        = string.Format(CultureInfo.InvariantCulture, "{0}/POX/IPrintServiceV1/ConvertUrlToPdf?sessionTokenId={1}&url={2}&marginLeft={3}&marginTop={4}", webserviceUrl, _dummySessionToken, HttpUtility.UrlEncode(textBoxUrl.Text), marginLeft, marginTop);
                HttpWebRequest  webrequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                HttpWebResponse response   = (HttpWebResponse)webrequest.GetResponse();
                literalHttpStatusMessage.Text = string.Empty;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    string xml    = new StreamReader(stream).ReadToEnd();
                    if (string.IsNullOrEmpty(xml))
                    {
                        literalHttpStatusMessage.Text = _errorMessage;
                    }
                }
                else
                {
                    literalHttpStatusMessage.Text = response.StatusDescription;
                }
                literalViewer.Text = "<embed id='pdfViewer' runat='server' width='100%' height='100%' src=" + url + "></embed>";
            }
            catch (TimeoutException ex)
            {
                literalHttpStatusMessage.Text = ex.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
            }
            catch (FileNotFoundException fileNotFoundEx)
            {
                literalHttpStatusMessage.Text = fileNotFoundEx.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, fileNotFoundEx.StackTrace, fileNotFoundEx.Message + fileNotFoundEx.StackTrace);
            }
            catch (WebException webEx)
            {
                literalHttpStatusMessage.Text = webEx.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, webEx.StackTrace, webEx.Message + webEx.StackTrace);
            }
            catch (HttpException httpException)
            {
                literalHttpStatusMessage.Text = httpException.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, httpException.StackTrace, httpException.Message + httpException.StackTrace);
            }
            catch (UriFormatException uriFormatException)
            {
                literalHttpStatusMessage.Text = uriFormatException.Message;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.MachineName, uriFormatException.StackTrace, uriFormatException.Message + uriFormatException.StackTrace);
            }
        }
        /// <summary>
        /// GetNumberOfPages
        /// </summary>
        /// <param name="sessionTokenId">sessionTokenId</param>
        /// <param name="extension">extension</param>
        /// <param name="url">url</param>
        /// <param name="marginLeft">marginLeft</param>
        /// <param name="marginTop">marginTop</param>
        /// <returns></returns>
        public int GetNumberOfPages(string sessionTokenId, string extension, string url, int marginLeft, int marginTop)
        {
            try
            {
                HttpContext httpContext = HttpContext.Current;
                string      domainName  = string.Format(CultureInfo.InvariantCulture, const_Domainformat,
                                                        httpContext.Request.Url.Scheme,
                                                        httpContext.Request.Url.Host,
                                                        httpContext.Request.Url.Port);

                XDocument xmlDocument = null;
                string    requestUrl  =
                    string.Format(ConfigurationManager.AppSettings[StaticConstants.Const_GetPageNumberFormat],
                                  domainName + ConfigurationManager.AppSettings[StaticConstants.Const_PrinterUrl],
                                  sessionTokenId,
                                  HttpUtility.UrlEncode(url),
                                  marginLeft,
                                  marginTop);

                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(requestUrl);
                webrequest.Method = StaticConstants.Const_Get;
                HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    string xml    = new StreamReader(stream).ReadToEnd();
                    if (!string.IsNullOrEmpty(xml))
                    {
                        xmlDocument = XDocument.Parse(xml);
                    }
                }
                return(Convert.ToInt32(xmlDocument.Root.Value));
            }
            catch (UriFormatException uriFormatException)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name,
                                     Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                     Environment.MachineName,
                                     uriFormatException.StackTrace,
                                     HttpUtility.UrlEncode(url) + uriFormatException.Message + uriFormatException.StackTrace);
                return(0);
            }
            catch (WebException webException)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name,
                                     Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                     Environment.MachineName,
                                     webException.StackTrace,
                                     HttpUtility.UrlEncode(url) + webException.Message + webException.StackTrace);
                return(0);
            }
            catch (Exception ex)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                LoggerHelperV1.Error(Assembly.GetExecutingAssembly().GetName().Name,
                                     Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                     Environment.MachineName,
                                     ex.StackTrace,
                                     HttpUtility.UrlEncode(url) + ex.Message + ex.StackTrace);
                return(0);
            }
        }
Example #18
0
        /// <summary>
        /// Return an image the of a html page
        /// A html file may be generated to a punk of images
        /// This method return a single image that specific in pageNumber parameter
        /// </summary>
        /// <param name="sessionTokenId">SessionTokenId given by user to authorize</param>
        /// <param name="url">The URL of a page that will be rendered</param>
        /// <param name="marginLeft">Value in integer that indicates the margin in the left of pdf file</param>
        /// <param name="marginTop">Value in integer that indicates the margin in the top of pdf file</param>
        /// <param name="format">Format of return image, currently we support BMP, PNG, GIF, JPG, JPEG</param>
        /// <param name="page">The specific page that return to user. The total number of pages can be got by call method GetNumberOfPages</param>
        /// <returns>Return an image stream</returns>
        Stream IPrintServiceV1.ConvertUrlToImage(string sessionTokenId, string url, int marginLeft, int marginTop, string format, int page)
        {
            Stream returnStream = null;

            format = format.ToUpper(CultureInfo.InvariantCulture);
            if (format == "PNG" || format == "BMP" || format == "GIF" || format == "JPG" || format == "JPEG")
            {
                if (marginLeft < 10000 && marginTop < 10000)
                {
                    string extension = string.Empty;
                    extension = GetExtension(url);
                    extension = extension.ToLower(CultureInfo.InvariantCulture);
                    try
                    {
                        bool isQualified = IsQualifiedUrl(url.ToString());
                        if (isQualified)
                        {
                            switch (extension)
                            {
                            case PDF:
                                returnStream = ConvertPdfToImage(url, marginLeft, marginTop, page);
                                break;

                            default:
                                returnStream = ConvertUrlToImage(url, marginLeft, marginTop, page);
                                break;
                            }
                        }
                    }
                    catch (UriFormatException uriFormatException)
                    {
                        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                        LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName,
                                             uriFormatException.StackTrace,
                                             HttpUtility.UrlEncode(url.ToString()) + uriFormatException.Message +
                                             uriFormatException.StackTrace);
                    }
                    catch (WebException webException)
                    {
                        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                        LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName,
                                             webException.StackTrace,
                                             HttpUtility.UrlEncode(url.ToString()) + webException.Message +
                                             webException.StackTrace);
                    }
                    catch (Exception ex)
                    {
                        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                        LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace,
                                             HttpUtility.UrlEncode(url.ToString()) + ex.Message + ex.StackTrace);
                    }
                    if (WebOperationContext.Current != null)
                    {
                        WebOperationContext.Current.OutgoingResponse.ContentType = GetMineType(format);
                        HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                        WebOperationContext.Current.OutgoingResponse.Headers.Add(cacheHeader,
                                                                                 string.Format(
                                                                                     CultureInfo.InvariantCulture,
                                                                                     "max-age={0}, must-revalidate",
                                                                                     CachingDuration));
                    }
                }
            }
            return(returnStream);
        }
 /// <summary>
 /// This method to add log to SRS Logger to monitor the CPU hang 100%
 /// </summary>
 /// <param name="stackTrace"></param>
 /// <param name="detail"></param>
 private void LogMonitorCPU(string stackTrace, string detail)
 {
     LoggerHelperV1.Warn(AssemblyName, AssemblyVersion, Environment.MachineName, stackTrace, detail);
 }
Example #20
0
 //
 // GET: /Home/
 /// <summary>
 /// Get copyright configuration information with specific projectID
 /// </summary>
 /// <param name="id">ProjectID</param>
 /// <returns></returns>
 public ActionResult Index(string project)
 {
     try
     {
         ProjectName = project;
         ViewData["control_type"] = new SelectList(new List <SelectListItem>
         {
             new SelectListItem()
             {
                 Selected = false, Text = "GitHub", Value = "GIT"
             },
             new SelectListItem()
             {
                 Selected = false,
                 Text     = "Team Foundation System",
                 Value    = "TFS"
             }
         }, "Value", "Text", "GIT");
         if (!string.IsNullOrEmpty(project))
         {
             Models.Copyright copy = Dal.CopyrightDb.LoadDbCopyrightConfigByProjectId(project);
             if (copy == null)
             {
                 copy = new Models.Copyright();
             }
             else
             {
                 ViewData["control_type"] = new SelectList(new List <SelectListItem>
                 {
                     new SelectListItem()
                     {
                         Selected = false,
                         Text     = "GitHub",
                         Value    = "GIT"
                     },
                     new SelectListItem()
                     {
                         Selected = false,
                         Text     = "Team Foundation System",
                         Value    = "TFS"
                     }
                 }, "Value", "Text", copy.ControlType.Trim());
                 CopyrightServiceV1Client copyrightService = new CopyrightServiceV1Client("BasicHttpBinding_ICopyrightServiceV1");
                 if (copyrightService.IsProcessing(copy.RepositoryUrl))
                 {
                     copy.ForceMessage  = "Forcing";
                     copy.RunningStatus = copyrightService.GetWorkingItemStatus(copy.RepositoryUrl);
                 }
             }
             copy.ProjectName = project;
             if (copy.RunningStatus == "")
             {
                 copy.RunningStatus = " waiting for next run";
             }
             return(View(copy));
         }
     }
     catch (Exception ex)
     {
         LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, ex.Message + ex.StackTrace);
     }
     return(View());
 }
Example #21
0
        // Put license key to Azure setting.

        #region IPrintServiceV1 Members

        /// <summary>
        /// Convert the HTML code from the specified URL to a PDF document and send the
        /// document as an attachment to the browser
        /// </summary>
        /// <param name="sessionTokenId">SessionTokenId given by user to authorize</param>
        /// <param name="url">The URL of a page that will be rendered</param>
        /// <param name="marginLeft"></param>
        /// <param name="marginTop"></param>
        /// <returns>a byte array that rendered as a PDF, will be null if error</returns>
        Stream IPrintServiceV1.ConvertUrlToPdf(string sessionTokenId, string url, int marginLeft, int marginTop)
        {
            Stream returnStream = null;

            if (marginLeft < 10000 && marginTop < 10000)
            {
                try
                {
                    bool isQualified = IsQualifiedUrl(url.ToString());
                    if (isQualified)
                    {
                        // Create a Doc object
                        XSettings.InstallRedistributionLicense(licenseKey);

                        using (Doc theDoc = new Doc())
                        {
                            //theDoc.SetInfo(0, "RenderDelay", "1000");
                            theDoc.HtmlOptions.UseScript        = true;
                            theDoc.HtmlOptions.UseActiveX       = true;
                            theDoc.HtmlOptions.UseVideo         = true;
                            theDoc.HtmlOptions.PageCacheEnabled = true;
                            theDoc.HtmlOptions.Timeout          = 120000; // 120 seconds
                            theDoc.Rect.Inset(marginLeft, marginTop);     // add margin

                            // Add the first page of HTML. Save the returned ID as this will be used to add subsequent pages
                            theDoc.Page = theDoc.AddPage();

                            int theID = theDoc.AddImageUrl(url.ToString());

                            // Now chain subsequent pages together. Stop when reach a page which wasn't truncated.
                            while (true)
                            {
                                if (!theDoc.Chainable(theID))
                                {
                                    break;
                                }
                                theDoc.Page = theDoc.AddPage();
                                theDoc.Rendering.DotsPerInch = constDotPerInches; // DPI
                                theDoc.Rendering.SaveQuality = constSaveQuality;  // Quality
                                theID = theDoc.AddImageToChain(theID);
                            }

                            // After adding the pages we can flatten them. We can't do this until after the pages have been added
                            // because flattening will invalidate our previous ID and break the chain.
                            for (int i = 1; i <= theDoc.PageCount; i++)
                            {
                                theDoc.PageNumber = i;
                                theDoc.Flatten();
                            }
                            // Get pdf data from the Doc object
                            returnStream = new MemoryStream(theDoc.GetData());
                            //returnByte = theDoc.GetData();

                            theDoc.Clear();
                        }
                    }

                    //TO-DO: Add the HTTP Status Code 403 (Forbidden) when the url is not in supported list
                }
                catch (UriFormatException uriFormatException)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName,
                                         uriFormatException.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + uriFormatException.Message +
                                         uriFormatException.StackTrace);
                    returnStream = null;
                }
                catch (WebException webException)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, webException.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + webException.Message +
                                         webException.StackTrace);
                    returnStream = null;
                }
                catch (Exception ex)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace,
                                         HttpUtility.UrlEncode(url.ToString()) + ex.Message + ex.StackTrace);
                    returnStream = null;
                }
                if (WebOperationContext.Current != null)
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
                    HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                    WebOperationContext.Current.OutgoingResponse.Headers.Add(cacheHeader,
                                                                             string.Format(CultureInfo.InvariantCulture,
                                                                                           "max-age={0}, must-revalidate",
                                                                                           CachingDuration));
                    //Add one day caching
                }
            }
            return(returnStream);
        }