Exemplo n.º 1
0
    public HtmlTable CreateForm(int JobID, HttpServerUtility server)
    {
        List<JobInfo> info = Brentwood.ListJobInfoByJob(JobID);
        List<JobAsset> assets = Brentwood.ListJobAssetsByJobID(JobID);

        HtmlTable table = new HtmlTable();

        foreach (JobInfo item in info)
        {
            table.Rows.Add(CreateRow(item));
        }

        foreach (JobAsset item in assets)
        {
            table.Rows.Add(CreateAssetRow(item, server));
        }

        Job job = Brentwood.GetJob(JobID);
        List<HtmlTableRow> rows = AddAdditionalInfo(job);

        foreach(HtmlTableRow item in rows)
            table.Rows.Add(item);

        return table;
    }
    /// <summary>
    /// 取得主視覺的內容
    /// </summary>
    /// <param name="server"></param>
    /// <param name="mainAdvNodeId">主視覺設定檔代碼</param>
    /// <returns>主視覺的內容</returns>
    public static string GetMainAdvContent(HttpServerUtility server, int mainAdvNodeId)
    {
        string content = string.Empty;

        PostFactory postFactory = new PostFactory();
        IPostService postService = postFactory.GetPostService();

        NodeVO nodeVO = postService.GetNodeById(mainAdvNodeId);
        if (nodeVO != null)
        {
            if (nodeVO.UType == NodeVO.UnitType.Flash)
            {
                string advFile = server.MapPath("~/template/") + "main-adv-flash01.txt";
                string fileContent = File.ReadAllText(advFile, System.Text.Encoding.UTF8);

                content = fileContent.Replace("(#FILENAME)", nodeVO.PicFileName);
            }
            //暫時不用圖片,僅flash
            //else if (nodeVO.UType == NodeVO.UnitType.Pic)
            //{
            //    string advFile = server.MapPath("~/template/") + "main-adv-pic01.txt";
            //    string fileContent = File.ReadAllText(advFile, System.Text.Encoding.UTF8);

            //    content = fileContent.Replace("(#FILENAME)", nodeVO.PicFileName);
            //}
        }

        return content;
    }
Exemplo n.º 3
0
 private static void CheckTable(GtfsTable gtfsTable, String extension, HttpServerUtility server)
 {
     gtfsTable.FilePath = String.Format("/parsed/{0}{1}", gtfsTable.Name, extension);
     var fileInfo = new FileInfo(server.MapPath(gtfsTable.FilePath));
     gtfsTable.Extension = fileInfo.Extension;
     gtfsTable.Exists = fileInfo.Exists;
     gtfsTable.LastUpdateUtc = fileInfo.LastWriteTimeUtc;
 }
Exemplo n.º 4
0
    private HtmlTableRow CreateAssetRow(JobAsset item, HttpServerUtility server)
    {
        HtmlTableRow row = new HtmlTableRow();
        string filename = Path.GetFileName(item.Filepath);
        row.Cells.Add(CreateCell("Job Asset: " + filename));
        HtmlTableCell cell = new HtmlTableCell();
        cell = new HtmlTableCell();
        string url = WebUtils.ResolveVirtualPath(item.Filepath).Replace("~", "..");
        cell.InnerHtml = String.Format("<a href=\"{0}\" target=\"blank\">{1}</a>", url, "Open File");
        row.Cells.Add(cell);

        return row;
    }
Exemplo n.º 5
0
    public static MatlabRunner getMatlabRunner(HttpApplicationState Application, HttpServerUtility Server)
    {
        MatlabRunner m = null;
        m = (MatlabRunner)Application.Get("MatlabRunner");

        if( null == m )
        {
            m = new MatlabRunner(Server, Application);
            Application.Set("MatlabRunner", m);
        }

        return m;
    }
    public static string GetMainTopAdvPic(HttpServerUtility server, int m_PostId1)
    {
        string content = string.Empty;

        WebPageHelper webPageHelper = new WebPageHelper();
        PostFactory postFactory = new PostFactory();
        IPostService postService = postFactory.GetPostService();

        PostVO podeVO = postService.GetPostById(m_PostId1);
        if (podeVO != null)
        {
            string advFile = server.MapPath("~/template/") + "main-adv-pic01.txt";
            string fileContent = File.ReadAllText(advFile, System.Text.Encoding.UTF8);

            content = fileContent.Replace("(#FILENAME)", webPageHelper.GetContent(podeVO, "PicFileName"));
        }

        return content;
    }
Exemplo n.º 7
0
    public HtmlTable CreateForm(int JobID, HttpServerUtility server)
    {
        Job job = Brentwood.GetJob(JobID);
        List<JobInfo> info = Brentwood.ListJobInfoByJob(JobID);
        List<JobAsset> assets = Brentwood.ListJobAssetsByJobID(JobID);

        HtmlTable table = new HtmlTable();

        table.Rows.Add(CreateRow("Order ID No:", job.JobID.ToString()));

        foreach (JobInfo item in info)
            table.Rows.Add(CreateRow(item));

        table.Rows.Add(CreateRow("Estimated Delivery Date:", ((DateTime)job.PromiseDate).ToString("dd MMM yyyy hh:mm tt")));

        foreach (JobAsset item in assets)
            table.Rows.Add(CreateAssetRow(item, server));

        return table;
    }
Exemplo n.º 8
0
    public Album findById(int id, HttpServerUtility Server)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("/App_Data/data.xml"));

        XmlNodeList nodeList = doc.GetElementsByTagName("album");
        foreach (XmlNode node in nodeList)
        {
            if (node["id"].InnerText == id.ToString())
            {
                return new Album(
                    id,
                    node["artist"].InnerText,
                    node["title"].InnerText,
                    decimal.Parse(node["price"].InnerText)
                    );
            }
        }
        return null;
    }
Exemplo n.º 9
0
    public MatlabRunner(HttpServerUtility Server, HttpApplicationState Application)
    {
        m_server = Server;
        m_app = Application;

        m_matlab = new EngMATLib.EngMATAccess();
        m_matlab.Evaluate("cd('" + m_server.MapPath("App_Data") + "');");

        m_queue = new Queue<FmriRequest>();
        m_doneList = new List<FmriRequest>();

        m_newItemEvent = new AutoResetEvent(false);
        m_stopEvent = new ManualResetEvent(false);
        m_waitables = new WaitHandle[] { m_newItemEvent, m_stopEvent };

        m_app["ReqHist"] = readFromHistory();

        m_thread = new Thread(WorkLoop);
        m_thread.Start();
    }
Exemplo n.º 10
0
        internal static string GetFullFileName(string path, string contentType)
        {
            var href     = Path.GetFileNameWithoutExtension(path);
            var category = GetCategoryFromPath(path);

            var hrefTokenSource = href;

            if (Uri.IsWellFormedUriString(href, UriKind.Relative))
            {
                hrefTokenSource = (SecureHelper.IsSecure() ? "https" : "http") + href;
            }

            var hrefToken = string.Concat(HttpServerUtility.UrlTokenEncode(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(hrefTokenSource))));

            if (string.Compare(contentType, "text/css", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return(string.Format("/{0}/css/{1}.css", category, hrefToken));
            }

            return(string.Format("/{0}/javascript/{1}.js", category, hrefToken));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Application_Start
        /// Executes on the first web request into the portal application,
        /// when a new DLL is deployed, or when web.config is modified.
        /// </summary>
        /// <remarks>
        /// - global variable initialization
        /// </remarks>
        protected void Application_Start(object sender, EventArgs e)
        {
            HttpServerUtility httpServerUtility = HttpContext.Current.Server;

            //global variable initialization
            Globals.ServerName = httpServerUtility.MachineName;

            if (HttpContext.Current.Request.ApplicationPath == "/")
            {
                Globals.ApplicationPath = "";
            }
            else
            {
                Globals.ApplicationPath = HttpContext.Current.Request.ApplicationPath;
            }
            Globals.ApplicationMapPath = AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.Length - 1);
            Globals.ApplicationMapPath = Globals.ApplicationMapPath.Replace("/", "\\");

            Globals.HostPath    = Globals.ApplicationPath + "/Portals/_default/";
            Globals.HostMapPath = httpServerUtility.MapPath(Globals.HostPath);

            Globals.AssemblyPath = Globals.ApplicationMapPath + "\\bin\\dotnetnuke.dll";

            //Check whether the current App Version is the same as the DB Version
            CheckVersion();

            //Cache Mapped Directory(s)
            CacheMappedDirectory();

            //log APPLICATION_START event
            LogStart();

            //Start Scheduler
            StartScheduler();

            //Process any messages in the EventQueue for the Application_Start event
            EventQueueController oEventController = new EventQueueController();

            oEventController.ProcessMessages("Application_Start");
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets and creates thumbnail.
        /// </summary>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="imagePath">The image path.</param>
        /// <returns></returns>
        public static string GetAndCreateProductThumbnail(int width, int height, string imagePath)
        {
            string            thumbnail = imagePath.Replace("product/", string.Format("product/thumbs/{0}x{1}_", width, height));
            HttpServerUtility server    = CurrentHttpContext.Server;

            if (!File.Exists(server.MapPath(thumbnail)))
            {
                if (File.Exists(server.MapPath(imagePath)))
                {
                    //Thumbnails don't exist so lets generate them...
                    string fileName = imagePath.Substring(imagePath.LastIndexOf("/") + 1);
                    using (FileStream fs = File.Open(server.MapPath(imagePath), FileMode.Open, FileAccess.Read, FileShare.None)) {
                        ImageProcess.ResizeAndSave(fs, fileName, server.MapPath(@"~/repository/product/thumbs/"), width, height);
                    }
                }
                else
                {
                    return(imagePath);
                }
            }
            return(thumbnail);
        }
Exemplo n.º 13
0
        public bool validateUploadData(HttpServerUtility Server)
        {
            string fileName      = Path.GetFileName(myFile.FileName);
            string fileExtension = Path.GetExtension(myFile.FileName);
            string fileLocation  = Server.MapPath("~/App_Data/" + fileName);

            myFile.SaveAs(fileLocation);

            //Check whether file extension is xls or xslx

            if (fileExtension == ".xls")
            {
                //connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
            }
            else if (fileExtension == ".xlsx")
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                //connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + @";Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
            }


            int nFileLen = myFile.ContentLength;

            if (nFileLen == 0)
            {
                throw new ArgumentNullException("No file was uploaded");
            }


            // Check file extension (must be JPG)
            if (!(System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".xls" || System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".xlsx"))
            {
                throw new ArgumentNullException("Not a Valid Excel File");
            }


            return(true);
        }
Exemplo n.º 14
0
 public static double RequestCountByIP(HttpServerUtility server, HttpApplicationState ha, HttpRequest hr, long iIncrementBy)
 {
     try
     {
         string   sIP     = (hr.UserHostAddress ?? "").ToString();
         string   sKey    = "rcbip" + sIP;
         string   sClean  = AppCache(sKey, ha);
         DateTime dtClean = DateTime.Now;
         if (sClean.Length > 0)
         {
             dtClean = Convert.ToDateTime(sClean);
         }
         string sValue = AppCache(sKey + "_count", ha);
         double dCount = 0;
         if (sValue.Length > 0)
         {
             dCount = Conversion.Val(sValue);
         }
         double dtSecs = DateAndTime.DateDiff(DateInterval.Second, dtClean, DateTime.Now);
         if (dtSecs > 60)
         {
             //Clear the value
             AppCache(sKey, DateTime.Now.ToString(), server, ha);
             AppCache(sKey + "_count", "0", server, ha);
             return(0);
         }
         else
         {
             AppCache(sKey + "_count", Strings.Trim((dCount + iIncrementBy).ToString()), server, ha);
         }
         return(dCount);
         //How many hits from ip over last minute
     }
     catch (Exception ex)
     {
         clsStaticHelper.Log("Request count by ip " + ex.Message);
         return(0);
     }
 }
Exemplo n.º 15
0
        public void CanGetDocumentWithBase64EncodedKey()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();
                string complexKey        = HttpServerUtility.UrlTokenEncode(new byte[] { 1, 2, 3, 4, 5 });

                var expectedDoc =
                    new Document()
                {
                    { "hotelId", complexKey }
                };

                var batch = new IndexBatch(new[] { new IndexAction(expectedDoc) });
                client.Documents.Index(batch);
                SearchTestUtilities.WaitForIndexing();

                DocumentGetResponse getResponse = client.Documents.Get(complexKey, expectedDoc.Keys);
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                SearchAssert.DocumentsEqual(expectedDoc, getResponse.Document);
            });
        }
 public static byte[] Decode(CookieProtection cookieProtection, string data)
 {
     byte[] array = HttpServerUtility.UrlTokenDecode(data);
     if (array == null || cookieProtection == CookieProtection.None)
     {
         return(array);
     }
     if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption)
     {
         array = EncryptOrDecryptData(false, array, null, 0, array.Length);
         if (array == null)
         {
             return(null);
         }
     }
     if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation)
     {
         if (array.Length <= 20)
         {
             return(null);
         }
         byte[] array2 = new byte[array.Length - 20];
         Buffer.BlockCopy(array, 0, array2, 0, array2.Length);
         byte[] array3 = HashData(array2, null, 0, array2.Length);
         if (array3 == null || array3.Length != 20)
         {
             return(null);
         }
         for (int i = 0; i < 20; i++)
         {
             if (array3[i] != array[array2.Length + i])
             {
                 return(null);
             }
         }
         array = array2;
     }
     return(array);
 }
Exemplo n.º 17
0
        public void Protect()
        {
            // Arrange
            byte[] expectedInputBytes   = new byte[] { 1, 2, 3, 4, 5 };
            byte[] expectedOutputBytes  = new byte[] { 6, 7, 8, 9, 10 };
            string expectedOutputString = HttpServerUtility.UrlTokenEncode(expectedOutputBytes);

            Func <byte[], string[], byte[]> protectThunk = (input, purposes) =>
            {
                Assert.Equal(expectedInputBytes, input);
                Assert.Equal(new string[] { "System.Web.Helpers.AntiXsrf.AntiForgeryToken.v1" }, purposes);
                return(expectedOutputBytes);
            };

            MachineKey45CryptoSystem cryptoSystem = new MachineKey45CryptoSystem(protectThunk, null);

            // Act
            string output = cryptoSystem.Protect(expectedInputBytes);

            // Assert
            Assert.Equal(expectedOutputString, output);
        }
 public static string Encrypt <T>(string value, string password) where T : SymmetricAlgorithm, new()
 {
     byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector);
     byte[] saltBytes   = Encoding.ASCII.GetBytes(_salt);
     byte[] valueBytes  = Encoding.UTF8.GetBytes(value);
     byte[] encrypted;
     using (T cipher = new T()) {
         PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(_stuffing, saltBytes, _hash, _iterations);
         byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);
         cipher.Mode = CipherMode.CBC;
         using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {
             MemoryStream to = new MemoryStream();
             using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {
                 writer.Write(valueBytes, 0, valueBytes.Length);
                 writer.FlushFinalBlock();
                 encrypted = to.ToArray();
             }
         }
         cipher.Clear();
     }
     return(HttpServerUtility.UrlTokenEncode(encrypted));
 }
Exemplo n.º 19
0
        /// <summary>
        /// 全局的异常处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            string            s      = HttpContext.Current.Request.Url.ToString();
            HttpServerUtility server = HttpContext.Current.Server;

            if (server.GetLastError() != null)
            {
                // Exception lastError = server.GetLastError().GetBaseException();
                Exception lastError = server.GetLastError();
                // 此处进行异常记录,可以记录到数据库或文本,也可以使用其他日志记录组件。

                //  ExceptionHandler.WriteException(lastError);
                new SysExceptionModelsController().WriteException(lastError);



                Application["LastError"] = lastError;

                int statusCode = HttpContext.Current.Response.StatusCode;



                string exceptionOperator = "/SysExceptionModels/Error";
                try
                {
                    if (!String.IsNullOrEmpty(exceptionOperator))
                    {
                        exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
                        string url    = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
                        string script = String.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
                        Response.Write(script);

                        Response.End();
                    }
                }
                catch { }
            }
        }
Exemplo n.º 20
0
        void Application_Error(object sender, EventArgs e)
        {
            //// Code that runs when an unhandled error occurs

            //// Get the exception object.
            //Exception exc = Server.GetLastError();

            //// Handle HTTP errors
            //if (exc.GetType() == typeof(HttpException))
            //{
            //    // The Complete Error Handling Example generates
            //    // some errors using URLs with "NoCatch" in them;
            //    // ignore these here to simulate what would happen
            //    // if a global.asax handler were not implemented.
            //    if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
            //        return;

            //    //Redirect HTTP errors to HttpError page
            //    Server.Transfer("HttpErrorPage.aspx");
            //}

            //// For other kinds of errors give the user some information
            //// but stay on the default page
            //Response.Write("<h2>Global Page Error</h2>\n");
            //Response.Write("<p>" + exc.Message + "</p>\n");
            //Response.Write("Return to the <a href='Default.aspx'>Default Page</a>\n");

            //// Log the exception and notify system operators
            //ExceptionUtility.LogException(exc, "DefaultPage");
            //ExceptionUtility.NotifySystemOps(exc);

            //// Clear the error from the server
            //Server.ClearError();

            // Use HttpContext.Current to get a Web request processing helper
            HttpServerUtility server    = HttpContext.Current.Server;
            Exception         exception = server.GetLastError();
        }
Exemplo n.º 21
0
    //Fungerar som en omstart och rensar alla inmatningsrutor odyl + display:
    protected void button_Refresh_TB_Click(object sender, EventArgs e)
    {
        HttpServerUtility server    = this.Server;
        String            retursida = "~/Default.aspx";

        try
        {
            Refresh_TB rtb = new Refresh_TB();
            rtb.button_Refresh_TB(server, retursida);
        }
        catch (FormatException err)
        {
            //Rensar display från text och gridviews
            clr.Clean_surfaces(this.Page);

            string mess = "<h2>[Page]Skivor.Refresh_TB:FormatException</h2>";
            mess += "<h2>Felmeddelande: " + err.Message + "</h2>";
            display.InnerHtml = mess;
        }
        catch (MySqlException err)
        {
            //Rensar display från text och gridviews
            clr.Clean_surfaces(this.Page);

            string mess = "<h2>[Page]Skivor.Refresh_TB:MySqlException</h2>";
            mess += "<h2>Felmeddelande: " + err.Message + "</h2>";
            display.InnerHtml = mess;
        }
        catch (System.Exception err)
        {
            //Rensar display från text och gridviews
            clr.Clean_surfaces(this.Page);

            string mess = "<h2>[Page]Skivor.Refresh_TB:System.Exception</h2>";
            mess += "<h2>Felmeddelande: " + err.Message + "</h2>";
            display.InnerHtml = mess;
        }
    }
Exemplo n.º 22
0
        /// <summary>
        /// Binds the data.
        /// </summary>
        /// <param name="searchCriteria">The search criteria.</param>
        private void bindData(MSearchCriteria searchCriteria)
        {
            try
            {
                HttpServerUtility mServer          = Server;
                string            mAction          = GWWebHelper.GetQueryValue(HttpContext.Current.Request, "Action");
                MFunctionProfile  mFunctionProfile = FunctionUtility.GetProfile(mAction);
                m_DirectoryProfile = DirectoryUtility.GetProfileByFunction(mFunctionProfile.Id);
                string    mDirectoryPath = m_DirectoryProfile.Directory + m_CurrentDirectory;
                DataTable mDataTable     = FileUtility.GetDirectoryTableData(mDirectoryPath, m_DirectoryProfile, false);
                SortTable mSorter        = new SortTable();
                string    mColName       = searchCriteria.OrderByColumn;
                mSorter.Sort(mDataTable, mColName, searchCriteria.OrderByDirection);

                DataView mView = mDataTable.DefaultView;
                mView.Sort = "type desc";
                mDataTable = DataHelper.GetTable(ref mView);
                //mDataTable = DataHelper.GetPageOfData(ref mDataTable, ref searchCriteria);
                string mSort = "type desc, " + searchCriteria.OrderByColumn + " " + searchCriteria.OrderByDirection;
                mDataTable = DataHelper.GetPageOfData(ref mDataTable, mSort, searchCriteria);
                if (mDataTable != null && mDataTable.Rows.Count > 0)
                {
                    DataView mDataView = mDataTable.DefaultView;
                    recordsReturned.Value    = mDataTable.Rows[0][DataHelper.TotalRowColumnName].ToString();
                    searchResults.DataSource = mDataTable;
                    searchResults.DataBind();
                }
                else
                {
                    noResults.Visible = true;
                }
            }
            catch (DirectoryNotFoundException)
            {
                litErrorMSG.Visible = true;
                litErrorMSG.Text    = "The Directory has not been setup or is unavalible.";
            }
        }
Exemplo n.º 23
0
 public static bool SaveFiles(HttpPostedFile file, HttpServerUtility server, string folderPath, out string path)
 {
     try
     {
         if (file != null && file.ContentLength > 0)
         {
             var fileName   = Path.GetFileName(file.FileName);
             var extension  = Path.GetExtension(fileName);
             var name       = Guid.NewGuid();
             var serverPath = Path.Combine(server.MapPath(folderPath), name + extension);
             file.SaveAs(serverPath);
             path = name + extension;
             return(true);
         }
         path = string.Empty;
         return(false);
     }
     catch (Exception)
     {
         path = string.Empty;
         return(false);
     }
 }
Exemplo n.º 24
0
        private static string GetSiteUnsubscribeLink(NoticeMessage message, MailWhiteLabelSettings settings)
        {
            var mail = message.Recipient.Addresses.FirstOrDefault(r => r.Contains("@"));

            if (string.IsNullOrEmpty(mail))
            {
                return(string.Empty);
            }

            var format = CoreContext.Configuration.CustomMode
                             ? "{0}/unsubscribe/{1}"
                             : "{0}/Unsubscribe.aspx?id={1}";

            var site = settings == null
                           ? MailWhiteLabelSettings.DefaultMailSiteUrl
                           : settings.SiteUrl;

            return(string.Format(format,
                                 site,
                                 HttpServerUtility.UrlTokenEncode(
                                     Security.Cryptography.InstanceCrypto.Encrypt(
                                         Encoding.UTF8.GetBytes(mail.ToLowerInvariant())))));
        }
Exemplo n.º 25
0
        public string UploadFile(ref HttpPostedFile FileUploaded, HttpServerUtility context)
        {
            String FileName   = Path.GetFileName(FileUploaded.FileName);
            String Extension  = Path.GetExtension(FileUploaded.FileName);
            String FolderPath = GetConfig("FilesUploadedPath").ToString();

            if (!Directory.Exists(context.MapPath(FolderPath)))
            {
                System.IO.Directory.CreateDirectory(context.MapPath(FolderPath));
            }
            if (context != null)
            {
                String FilePath = context.MapPath(FolderPath + FileName + Extension);
                if (File.Exists(FilePath))
                {
                    FileName = FileName + "_" + Guid.NewGuid();
                    FilePath = context.MapPath(FolderPath + FileName + Extension);
                }
                FileUploaded.SaveAs(FilePath);
                return(FileName + Extension);
            }
            return("");
        }
Exemplo n.º 26
0
        /// <summary>Decode an item from a url token.</summary>
        /// <typeparam name="T">The item type.</typeparam>
        /// <param name="token">The item token.</param>
        /// <returns>The item instance.</returns>
        public static T Decode <T>(string token)
        {
            var rsa = new RSACryptoServiceProvider();
            var key = ConfigurationManager.AppSettings["EncryptionKey"];

            if (string.IsNullOrEmpty(key))
            {
                throw new Exception("AppSetting 'EncryptionKey' is missing");
            }
            rsa.ImportCspBlob(Convert.FromBase64String(key));
            var data = HttpServerUtility.UrlTokenDecode(token);

            data = rsa.Decrypt(data, true);

            using (var memoryStream = new MemoryStream(data))
            {
                using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    using (var bsonReader = new BsonReader(gzipStream))
                        return(JsonSerializer.CreateDefault().Deserialize <T>(bsonReader));
                }
            }
        }
        private void GenerateMessageBody(MailMessage msg, WebBaseEventCollection events, DateTime lastNotificationUtc, int discardedSinceLastNotification, int eventsInBuffer, int notificationSequence, EventNotificationType notificationType, int eventsInNotification, int eventsRemaining, int messagesInNotification, int eventsLostDueToMessageLimit, int messageSequence, out bool fatalError)
        {
            StringWriter writer            = new StringWriter(CultureInfo.InstalledUICulture);
            MailEventNotificationInfo data = new MailEventNotificationInfo(msg, events, lastNotificationUtc, discardedSinceLastNotification, eventsInBuffer, notificationSequence, notificationType, eventsInNotification, eventsRemaining, messagesInNotification, eventsLostDueToMessageLimit, messageSequence);

            CallContext.SetData("_TWCurEvt", data);
            try
            {
                TemplatedMailErrorFormatterGenerator errorFormatterGenerator = new TemplatedMailErrorFormatterGenerator(events.Count + eventsRemaining, this._detailedTemplateErrors);
                HttpServerUtility.ExecuteLocalRequestAndCaptureResponse(this._templateUrl, writer, errorFormatterGenerator);
                fatalError = errorFormatterGenerator.ErrorFormatterCalled;
                if (fatalError)
                {
                    msg.Subject = HttpUtility.HtmlEncode(System.Web.SR.GetString("WebEvent_event_email_subject_template_error", new object[] { notificationSequence.ToString(CultureInfo.InstalledUICulture), messageSequence.ToString(CultureInfo.InstalledUICulture), base.SubjectPrefix }));
                }
                msg.Body       = writer.ToString();
                msg.IsBodyHtml = true;
            }
            finally
            {
                CallContext.FreeNamedDataSlot("_TWCurEvt");
            }
        }
Exemplo n.º 28
0
        public static Dictionary <string, string> StringToListDictionary(String s)
        {
            var binFormatter = new BinaryFormatter();
            var mStream      = new MemoryStream();

            try
            {
                var bytes = HttpServerUtility.UrlTokenDecode(s);

                mStream.Write(bytes, 0, bytes.Length);
                mStream.Position = 0;

                Dictionary <string, string> listDictionary =
                    binFormatter.Deserialize(mStream) as Dictionary <string, string>;

                return(listDictionary);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 29
0
        private static IControllerFactory ConfigureFactory(HttpServerUtility httpServer)
        {
            // composition root, register all types with IoC container here.
            var container = new UnityContainer();

            string dataPath = httpServer.MapPath("~/App_Data/");

            container.RegisterType <IMetaDataRepository, MetaDataRepository>(new InjectionConstructor(dataPath));
            container.RegisterType <IArtRepository, ArtRepository>(new InjectionConstructor(dataPath));

            string username = ConfigurationManager.AppSettings["emailusername"];
            string password = ConfigurationManager.AppSettings["emailpassword"];
            string smtpHost = ConfigurationManager.AppSettings["smtphost"];

            container.RegisterType <IEmailer, Emailer>(new InjectionConstructor(username, password, smtpHost));

            string storageAccount = ConfigurationManager.AppSettings["storageaccount"];
            string accountKey     = ConfigurationManager.AppSettings["accountkey"];

            container.RegisterInstance <IPictureRepository>(new AzureBlobRepository(storageAccount, accountKey));

            return(new UnityControllerFactory(container));
        }
Exemplo n.º 30
0
        public static string Encrypt(string unencrypted)
        {
            if (string.IsNullOrEmpty(unencrypted))
            {
                return(string.Empty);
            }

            try
            {
                var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));

                if (encryptedBytes != null && encryptedBytes.Length > 0)
                {
                    return(HttpServerUtility.UrlTokenEncode(encryptedBytes));
                }
            }
            catch (Exception)
            {
                return(string.Empty);
            }

            return(string.Empty);
        }
Exemplo n.º 31
0
        public void _client_Received(WindowsFormsApp3.ClientSettings cs, string received)
        {
            var cmd = received.Split('|');

            switch (cmd[0])
            {
            case "CheieRSA":
                if (mUserNameTextBox.Text.Trim() == cmd[3].Trim())
                {
                    cheie.Exponent = HttpServerUtility.UrlTokenDecode(cmd[1]);
                    cheie.Modulus  = HttpServerUtility.UrlTokenDecode(cmd[2]);
                    byte[] DataToEncrypt = System.Text.Encoding.UTF8.GetBytes(mPasswordTextBox.Text);

                    byte[] parolaCriptata = e.RSAEncrypt(cheie, false, DataToEncrypt);
                    string qwe            = HttpServerUtility.UrlTokenEncode(parolaCriptata);
                    //   MessageBox.Show("parola criptata de la client::::" + qwe);
                    //MessageBox.Show("Exponent:::::::::::" + HttpServerUtility.UrlTokenEncode(cheie.Exponent));
                    //MessageBox.Show("Modul:::::::::::" + HttpServerUtility.UrlTokenEncode(cheie.Modulus));

                    Client.Send("ParolaCriptataRSA|" + qwe.Trim() + "|" + cmd[3].Trim());
                }

                break;

            case "LogInSuccessful":
                // MessageBox.Show("1");
                if (mUserNameTextBox.Text.Trim() == cmd[1].Trim())
                {
                    Client.Connected += Client_Connected;
                    Client.Connect(ip, 3000);
                    Client.Send("Connect|" + mUserNameTextBox.Text.Trim() + "|connected");
                }
                //  CloseForm();
                //   MessageBox.Show("2");
                break;
            }
        }
Exemplo n.º 32
0
 public static ModelsConfig GetModelsConfig()
 {
     if (SysContext.IsDev)
     {
         DbContext     currentDb    = SysContext.GetCurrentDb();
         List <string> list         = currentDb.Fetch <string>("select ModelName from core_model", new object[0]);
         ModelsConfig  modelsConfig = new ModelsConfig();
         foreach (string item in list)
         {
             modelsConfig.models.Add(GetModelByName(item));
         }
         return(modelsConfig);
     }
     else
     {
         string modelsPath = new HttpServerUtility(HttpContext.Current).MapPath("~/Service/models.xml");
         if (EnabledCache)
         {
             ModelsConfig modelsConfig = CacheHelper.GetCache("models.xml") as ModelsConfig;
             if (modelsConfig != null)
             {
                 return(modelsConfig);
             }
         }
         if (!File.Exists(modelsPath))
         {
             return(null);
         }
         string       modelsContent = File.ReadAllText(modelsPath);
         ModelsConfig modelsConfig2 = XmlHelper.XmlDeserialize <ModelsConfig>(modelsContent, Encoding.UTF8);
         if (EnabledCache)
         {
             CacheHelper.SetCache("models.xml", (object)modelsConfig2, new CacheDependency(modelsPath));
         }
         return(modelsConfig2);
     }
 }
Exemplo n.º 33
0
 public void ProcessRequest(HttpContext context)
 {
     context.Response.Buffer          = true;
     context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1.0);
     context.Response.AddHeader("pragma", "no-cache");
     context.Response.AddHeader("cache-control", "");
     context.Response.CacheControl = "no-cache";
     context.Response.ContentType  = "text/plain";
     this.Request  = context.Request;
     this.Response = context.Response;
     this.Server   = context.Server;
     this.Context  = context;
     try
     {
         Stream s = HttpContext.Current.Request.InputStream;
         byte[] b = new byte[s.Length];
         s.Read(b, 0, (int)s.Length);
         this.postStr = Encoding.UTF8.GetString(b);
         this.token   = PubFunction.curParameter.strWeiXinToken;
         this.Log(this.postStr);
         if (this.Request.HttpMethod.ToLower() == "get")
         {
             if (this.Request.QueryString["signature"] != null && !string.IsNullOrEmpty(this.Request.QueryString["signature"].ToString()))
             {
                 this.UrlValid();
             }
         }
         else
         {
             this.SendMsg();
         }
     }
     catch (Exception ex)
     {
         this.Log(ex.ToString());
     }
 }
Exemplo n.º 34
0
 public void ProcessRequest(HttpContext context)
 {
     this.m_server     = context.Server;
     this.m_context    = context;
     this.m_request    = this.m_context.Request;
     this.m_response   = this.m_context.Response;
     this.m_lgcContext = LogicContext.Current;
     this.m_lgcSession = LogicContext.GetLogicSession();
     this.m_pageParam  = new PageParameter();
     this.m_pageParam.ReadPageParameter(this.Request.QueryString);
     context.Server.ScriptTimeout = 3600;
     this.ParsePageParam();
     try
     {
         this.PrepareData();
     }
     catch (Exception ex)
     {
         this.m_promptMessage = ex.Message;
     }
     this.SendHeader();
     this.SendData();
     this.ClearData();
 }
Exemplo n.º 35
0
        public static string GetCodeFileString(HttpServerUtility server, CustomItemInformation info)
        {
            VelocityEngine velocity = new VelocityEngine();

            ExtendedProperties props = new ExtendedProperties();

            props.SetProperty("file.resource.loader.path", server.MapPath("."));             // The base path for Templates

            velocity.Init(props);

            //Template template = velocity.GetTemplate("template.tmp");
            NVelocity.Template template = velocity.GetTemplate("CustomItem.vm");

            VelocityContext context = new VelocityContext();

            context.Put("BaseTemplates", info.BaseTemplates);
            context.Put("CustomItemFields", info.Fields);
            context.Put("CustomItemInformation", info);

            StringWriter writer = new StringWriter();

            template.Merge(context, writer);
            return(writer.GetStringBuilder().ToString());
        }
Exemplo n.º 36
0
        public static string Encrypt(string toEncrypt, string key)
        {
            try
            {
                var des = new DESCryptoServiceProvider();
                var ms  = new MemoryStream();

                VerifyKey(ref key);

                des.Key = HashKey(key, des.KeySize / 8);
                des.IV  = HashKey(key, des.KeySize / 8);
                byte[] inputBytes = Encoding.UTF8.GetBytes(toEncrypt);

                var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputBytes, 0, inputBytes.Length);
                cs.FlushFinalBlock();

                return(HttpServerUtility.UrlTokenEncode(ms.ToArray()));
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("An error occured while running encryption. Exception : {0}", ex.Message), ex);
            }
        }
Exemplo n.º 37
0
    public CacheDataMgt(HttpServerUtility currservers)
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
        try
        {
            leaveTime    = int.Parse(APPConfig.GetAPPConfig().GetConfigValue("NodeCenterDataLeaveTime", ""));
            internalTime = int.Parse(WebConfigurationManager.AppSettings["NodeCenterDataInternalTime"].ToString());
        }
        catch (Exception ex)
        {
            leaveTime    = 1;
            internalTime = 3;
        }

        //cacheDataMgtTimer = new System.Threading.Timer(new TimerCallback(ExecUpdateCacheData), currservers, leaveTime * 1000, internalTime * 60000);

        //定时同步缓存数据
        ThreadStart AutoSynCacheData = new ThreadStart(ExecUpdateCacheData);
        Thread      AutoThread       = new Thread(AutoSynCacheData);

        AutoThread.Start();
    }
Exemplo n.º 38
0
        /// <summary>
        /// 打开站点
        /// </summary>
        /// <param name="sitePath"></param>
        /// <param name="server"></param>
        public static void Open(HttpServerUtility server)
        {
            //            string app_DataPath = Server.MapPath(APP_DATA);


            //            string sitePath = Server.MapPath("/");
            if (isStart)
            {
                return;
            }

            WboRegService.RegisterClass(typeof(Register));

            _server = server;

            _siteVirPath = HttpRuntime.AppDomainAppVirtualPath;


            _sitePhysicalPath = HttpRuntime.AppDomainAppPath;
            if (!_sitePhysicalPath.EndsWith("\\"))
            {
                _sitePhysicalPath += "\\";
            }


            schemaPath = _sitePhysicalPath + "App_Data\\";

            if (!_sitePhysicalPath.EndsWith("\\"))
            {
                _sitePhysicalPath += "\\";
            }

            _server = server;

            isStart = true;
        }
Exemplo n.º 39
0
Arquivo: Email.cs Projeto: radtek/Omi
        private static void EmbedInlineImage(MailMessage mailMessage, HttpServerUtility httpServerUtility)
        {
            //Embed images//

            var mailBody = mailMessage.Body;

            Regex           reImg           = new Regex(@"<img\s[^>]*>", RegexOptions.IgnoreCase);
            Regex           reSrc           = new Regex(@"src=(?:(['""])(?<src>(?:(?!\1).)*)\1|(?<src>\S+))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            MatchCollection matchCollection = reImg.Matches(mailBody);

            mailMessage.IsBodyHtml = true;

            foreach (Match match in matchCollection)
            {
                string src = string.Empty;

                if (reSrc.IsMatch(mailBody))
                {
                    Match mSrc = reSrc.Match(match.Groups[0].Value);

                    src = mSrc.Groups["src"].Value;
                }

                string imagePath    = src;
                string attachmentId = Path.GetFileName(imagePath);

                var attachmentImage = new Attachment(httpServerUtility.MapPath("~/" + imagePath));
                attachmentImage.ContentDisposition.Inline = true;
                attachmentImage.ContentId = attachmentId;
                mailMessage.Attachments.Add(attachmentImage);

                mailBody = mailBody.Replace(src, "cid:" + attachmentId);
            }
            mailMessage.Body = mailBody;
            //Embed images//
        }
Exemplo n.º 40
0
 /// <summary>
 /// IMGPath图路径,pathIndex指定路径前缀
 /// </summary>
 /// <param name="IMGPath"></param>
 /// <param name="Server"></param>
 /// <param name="fu"></param>
 /// <param name="pathIndex"></param>
 public static void uploadIMG(ref string IMGPath, HttpServerUtility Server, HttpPostedFile PostedFile, string FileName, string pathIndex)
 {
     try
     {
         string CurrentDatatime = Convert.ToString(System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
         IMGPath = pathIndex + CurrentDatatime + FileName.ToString();
         string IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + FileName.ToString();
         IMG_FullName = IMG_FullName.Replace("%", "");
         PostedFile.SaveAs(IMG_FullName);
     }
     catch
     {
     }
 }
Exemplo n.º 41
0
 public static void uploadIMG(ref string IMGPath, HttpServerUtility Server, FileUpload fu, string pathIndex)
 {
     uploadIMG(ref  IMGPath, Server, fu.PostedFile, fu.FileName, pathIndex);
 }
Exemplo n.º 42
0
 public static void FileDataBind(string Module, DropDownList ddlTemplate, DropDownList ddlFile, int PortalId, string LocalResourceFile, HttpServerUtility Server)
 {
     ddlFile.Items.Clear();
     ddlFile.Items.Add(new ListItem(Localization.GetString("selectFile", LocalResourceFile), ""));
     string dir = Server.MapPath(ddlTemplate.SelectedValue);
     if (!string.IsNullOrEmpty(ddlTemplate.SelectedValue) && Directory.Exists(dir))
     {
         var fileLst = GetFiles(dir, new string[] { ".cshtml", ".liquid", ".html", ".htm" });
         foreach (string item in fileLst)
         {
             int nb = item.LastIndexOf('\\');
             ddlFile.Items.Add(item.Substring(nb + 1));
         }
     }
 }
Exemplo n.º 43
0
 public static string GenerateDirectory(DropDownList ddlModule, DropDownList ddlType, TextBox tbxNewTemplate, int PortalId, HttpServerUtility Server)
 {
     return GenerateDirectory(ddlModule.SelectedValue, int.Parse(ddlType.SelectedValue), tbxNewTemplate.Text, PortalId, Server);
 }
Exemplo n.º 44
0
    public static void TemplateDataBind(string Module, int Type, DropDownList ddlTemplate, int PortalId, string LocalResourceFile, HttpServerUtility Server)
    {
        if (Type > 0)
        {
            ddlTemplate.Items.Clear();
            ddlTemplate.Items.Add(new ListItem(Localization.GetString("selectTemplate", LocalResourceFile), ""));
            string path = TemplateEditorUtils.GenerateDirectory(Module, Type, ddlTemplate.SelectedValue, PortalId, Server);
            if (!string.IsNullOrEmpty(path) && Directory.Exists(Server.MapPath(path)))
            {
                var dryLst = Directory.GetDirectories(Server.MapPath(path));

                foreach (string item in dryLst)
                {
                    int nb = item.LastIndexOf('\\');
                    ddlTemplate.Items.Add(item.Substring(nb + 1));
                }
            }
        }
        else
        {
            ddlTemplate.Items.Clear();
            ddlTemplate.Items.Add(new ListItem(Localization.GetString("selectTemplate", LocalResourceFile), ""));
        }
    }
Exemplo n.º 45
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="Server"></param>
 /// <param name="itemId"></param>
 /// <param name="mways">-1重新生成图片,0生成主图和附图,1仅主图,2仅附图</param>
 public static void MakeItemWaterMark(HttpServerUtility Server, long itemId, int mways)
 {
   
     
 }
Exemplo n.º 46
0
    public static void ModuleDataBind(DropDownList ddlModule, int PortalId, string LocalResourceFile, HttpServerUtility Server)
    {
        ddlModule.Items.Clear();
        ddlModule.Items.Add(Localization.GetString("selectModule", LocalResourceFile));

        DesktopModuleController mc = new DesktopModuleController();
        var dtmLst = DesktopModuleController.GetDesktopModules(PortalId).Values.Where(m => !m.IsAdmin && !m.FolderName.StartsWith("Admin"));
        foreach (DesktopModuleInfo dtm in dtmLst)
        {
            bool TemplateExist = false;
            for (int i = 1; i < 4; i++)
            {
                string[] pathLst = GetPathList(dtm.FolderName, i, PortalId);
                foreach (string pathitem in pathLst)
                {
                    if (Directory.Exists(Server.MapPath(pathitem)))
                    {
                        ddlModule.Items.Add(new ListItem(dtm.FriendlyName, dtm.FolderName));
                        TemplateExist = true;
                        break;
                    }
                }
                if (TemplateExist) break;
            }
        }
        ddlModule.Items.Add(new ListItem("Skins", "skins"));
        ddlModule.Items.Add(new ListItem("Containers", "containers"));
        ddlModule.Items.Add(new ListItem("Widgets", "widgets"));
    }
Exemplo n.º 47
0
 /// <summary>
 /// LargeIMGPath原图路径,IMGPath缩略图路径,pathIndex指定路径前缀,pathMid指定路径嵌入字符以区分原图或缩略图
 /// </summary>
 /// <param name="LargeIMGPath"></param>
 /// <param name="IMGPath"></param>
 /// <param name="Server"></param>
 /// <param name="fu"></param>
 /// <param name="pathIndex"></param>
 /// <param name="pathMid"></param>
 public static void uploadIMG(ref string LargeIMGPath, ref string IMGPath, HttpServerUtility Server, HttpPostedFile PostedFile, string FileName, string pathIndex, string pathMid)
 {
     try
     {
         string CurrentDatatime = Convert.ToString(System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
         //保存原图
         LargeIMGPath = pathIndex + CurrentDatatime + pathMid + FileName.ToString();
         LargeIMGPath = LargeIMGPath.Replace("%", "");
         string Large_IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + pathMid + FileName.ToString();
         Large_IMG_FullName = Large_IMG_FullName.Replace("%", "");
         PostedFile.SaveAs(Large_IMG_FullName);
         //生成缩略图并保存
         IMGPath = pathIndex + CurrentDatatime + FileName.ToString();
         IMGPath=IMGPath.Replace("%", "");
         string IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + FileName.ToString();
         IMG_FullName = IMG_FullName.Replace("%", "");
         Thumbnail.MakeThumbnail(Large_IMG_FullName, IMG_FullName, 300, 300, Enums.ImageThumbnail.HWC);
     }
     catch
     {
         throw new Exception("上传文件失败!");
     }
 }
Exemplo n.º 48
0
 public static string GetProjectsZDir(HttpServerUtility server)
 {
     return GetSiteSetting(server, "projectsz");
 }
Exemplo n.º 49
0
 public static string GenerateDirectory(string Module, int Type, string template, int PortalId, HttpServerUtility Server)
 {
     return GenerateDirectory(Module, Type, template, PortalId, Server, false);
 }
Exemplo n.º 50
0
    public static string GenerateDirectory(string Module, int Type, string template, int PortalId, HttpServerUtility Server, bool CheckDirExist)
    {
        string path = "";

        string[] pathLst = GetPathList(Module, Type, PortalId);
        if (pathLst.Length == 0) return "";
        path = pathLst[0];
        foreach (string item in pathLst)
        {
            if (!CheckDirExist || Directory.Exists(Server.MapPath(item)))
            {
                path = item + template;
                break;
            }
        }
        return path;
    }
Exemplo n.º 51
0
 public static void TemplateDataBind(DropDownList ddlModule, DropDownList ddlType, DropDownList ddlTemplate, int PortalId, string LocalResourceFile, HttpServerUtility Server)
 {
     TemplateDataBind(ddlModule.SelectedValue, int.Parse(ddlType.SelectedValue), ddlTemplate, PortalId, LocalResourceFile, Server);
 }
Exemplo n.º 52
0
 /// <summary>
 /// 删除文件
 /// </summary>
 /// <param name="path">绝对路径</param>
 /// <param name="Server"></param>
 public static void deleteFile(string path, HttpServerUtility Server)
 {
     if (path != null || path != "")
         try
         {
             FileInfo fi = new FileInfo(path);
             if (fi.Exists)//如果存在
             {
                 //删除文件.
                 fi.Delete();
             }
         }
         catch (Exception error)
         {
         }
 }
Exemplo n.º 53
0
 public static void deleteIMG(string IMGPath, HttpServerUtility Server)
 {
     if (IMGPath != null || IMGPath != "")
         try
         {
             string path = Server.MapPath(IMGPath);
             FileInfo fi = new FileInfo(path);
             if (fi.Exists)//如果存在
             {
                 //删除文件.
                 fi.Delete();
             }
         }
         catch (Exception error)
         {
         }
 }
Exemplo n.º 54
0
 public Crawler(string sourceUrl, HttpServerUtility server)
 {
     this.SourceUrl = sourceUrl;
     this.Server = server;
 }
Exemplo n.º 55
0
    public static void TemplateDataBind(string Module, DropDownList ddlTemplate, int PortalId, string LocalResourceFile, HttpServerUtility Server)
    {
        ddlTemplate.Items.Clear();
        ddlTemplate.Items.Add(new ListItem(Localization.GetString("selectTemplate", LocalResourceFile), ""));
        for (int type = 1; type < 4; type++)
        {
            string path = TemplateEditorUtils.GenerateDirectory(Module, type, "", PortalId, Server);
            if (!string.IsNullOrEmpty(path) && Directory.Exists(Server.MapPath(path)))
            {
                var dryLst = Directory.GetDirectories(Server.MapPath(path));
                if (dryLst.Count() > 0 && (Directory.GetFiles(Server.MapPath(path)).Count() == 0 || Module == "Blog"))
                {
                    foreach (string item in dryLst)
                    {
                        int nb = item.LastIndexOf('\\');
                        ddlTemplate.Items.Add(new ListItem(GetTypes()[type] + " - " + item.Substring(nb + 1), ReverseMapPath(item)));
                    }
                }
                else
                {
                    ddlTemplate.Items.Add(new ListItem(GetTypes()[type], path));

                }
            }
        }
        if (ddlTemplate.Items.Count == 2) {
            ddlTemplate.Items.RemoveAt(0);
            ddlTemplate.SelectedIndex = 0;
        }
    }