コード例 #1
0
        internal void SetValuesFromQuerySting()
        {
            HttpRequest       Request = HttpContext.Current.Request;
            HttpServerUtility Server  = HttpContext.Current.Server;

            if (!string.IsNullOrEmpty(Request.QueryString["TG"]))
            {
                TagList = Server.UrlDecode(Request.QueryString["TG"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["OS"]))
            {
                Status = (ObjectStatus)int.Parse(Request.QueryString["OS"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["SS"]))
            {
                ShowState = (ObjectShowState)int.Parse(Request.QueryString["SS"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["CR"]))
            {
                Copyright = int.Parse(Request.QueryString["CR"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["GC"]))
            {
                string[] geoLatLong = Request.QueryString["GC"].Split(',');
                double   geoLat, geoLong = double.MinValue;
                if (geoLatLong.Length == 2)
                {
                    if (double.TryParse(geoLatLong[0], out geoLat) && double.TryParse(geoLatLong[1], out geoLong))
                    {
                        Geo_Lat  = geoLat;
                        Geo_Long = geoLong;
                    }
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["ZP"]))
            {
                Zip = Server.UrlDecode(Request.QueryString["ZP"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["CI"]))
            {
                City = Server.UrlDecode(Request.QueryString["CI"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["RE"]))
            {
                Region = Server.UrlDecode(Request.QueryString["RE"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["CO"]))
            {
                CountryCode = Server.UrlDecode(Request.QueryString["CO"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["IsContest"]))
            {
                bool contestParam;
                IsContest = bool.TryParse(Request.QueryString["IsContest"], out contestParam) && contestParam;
            }
        }
コード例 #2
0
ファイル: DAL.cs プロジェクト: MzL777/PRA-RWAProjekt
        public static bool JeLiAdminAutenticiran(HttpSessionState Session, HttpServerUtility Server)
        {
            if (Session["Username"] != null && Session["Password"] != null)
            {
                var username = Server.UrlDecode(Session["Username"].ToString());
                var password = Server.UrlDecode(Session["Password"].ToString());

                if (AutenticirajAdministratora(username, password))
                {
                    return(true);
                }
            }
            return(false);
        }
コード例 #3
0
        public IHttpActionResult DeleteFiles(List <UIFileInfo> filesToDelete)
        {
            HttpServerUtility mServer           = HttpContext.Current.Server;
            string            mRetVal           = "Done";
            MDirectoryProfile mDirectoryProfile = DirectoryUtility.GetProfile(filesToDelete[0].FunctionSeqId);
            bool mExitLoop = false;

            foreach (UIFileInfo item in filesToDelete)
            {
                string mCurrentDirectory = mServer.UrlDecode(item.CurrentDirectory);
                if (mCurrentDirectory.Length == 0)
                {
                    mCurrentDirectory = mDirectoryProfile.Directory;
                }
                else
                {
                    mCurrentDirectory = mDirectoryProfile.Directory + mCurrentDirectory;
                }
                switch (item.FileType)
                {
                case "File":
                    string mFileName = mCurrentDirectory += "/" + mServer.UrlDecode(item.FileName);
                    mRetVal = FileUtility.DeleteFile(mFileName, mDirectoryProfile);
                    if (mRetVal.IndexOf("Successfully") == -1)
                    {
                        mExitLoop = true;
                    }
                    break;

                case "Folder":
                    mCurrentDirectory += "/" + mServer.UrlDecode(item.FileName);
                    mRetVal            = FileUtility.DeleteDirectory(mCurrentDirectory, mDirectoryProfile);
                    if (mRetVal.IndexOf("Successfully") == -1)
                    {
                        mExitLoop = true;
                    }
                    break;

                default:
                    break;
                }
                if (mExitLoop)
                {
                    break;
                }
            }
            return(this.Ok(mRetVal));
        }
コード例 #4
0
        public static void method(HttpServerUtility server, HttpRequest Request, DropDownList company, DropDownList model)
        {
            switch (server.UrlDecode(Request["company"]).ToString())
            {
            case "Thomas":
                company.SelectedValue = "Thomas Bus";

                //  if (!IsPostBack)
                //{
                foreach (Bus n in OverLand.bus)
                {
                    if (n.made == "Thomas Bus" /*&& model.Items.Count < 6*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //}
                break;

            case "Merce":
                company.SelectedValue = "Mercedes";
                //        if (!IsPostBack)
                //      {
                foreach (Bus n in OverLand.bus)
                {
                    if (n.made == "Mercedes" /*&& model.Items.Count < 5*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //    }
                break;
            }
        }
コード例 #5
0
        public static void method(HttpServerUtility server, HttpRequest Request, DropDownList company, DropDownList model)
        {
            switch (server.UrlDecode(Request["company"]).ToString())
            {
            case "Agusta":
                company.SelectedValue = "AgustaWestland";

                //  if (!IsPostBack)
                //{
                foreach (Helicopter n in Aerial.helicopter)
                {
                    if (n.made == "AgustaWestland" /*&& model.Items.Count < 6*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //}
                break;

            case "Bell":
                company.SelectedValue = "Bell";
                //        if (!IsPostBack)
                //      {
                foreach (Helicopter n in Aerial.helicopter)
                {
                    if (n.made == "Bell" /*&& model.Items.Count < 5*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //    }
                break;
            }
        }
コード例 #6
0
        public static void method(HttpServerUtility server, HttpRequest Request, DropDownList company, DropDownList model)
        {
            switch (server.UrlDecode(Request["company"]).ToString())
            {
            case "Cat":
                company.SelectedValue = "Cat";

                //  if (!IsPostBack)
                //{
                foreach (Truck n in OverLand.truck)
                {
                    if (n.made == "Cat" /*&& model.Items.Count < 6*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //}
                break;

            case "Ford":
                company.SelectedValue = "Ford";
                //        if (!IsPostBack)
                //      {
                foreach (Truck n in OverLand.truck)
                {
                    if (n.made == "Ford" /*&& model.Items.Count < 5*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //    }
                break;
            }
        }
コード例 #7
0
        public static void method(HttpServerUtility server, HttpRequest Request, DropDownList company, DropDownList model)
        {
            switch (server.UrlDecode(Request["company"]).ToString())
            {
            case "Cessna":
                company.SelectedValue = "Cessna";

                //  if (!IsPostBack)
                //{
                foreach (PrivateJet n in Aerial.privatejet)
                {
                    if (n.made == "Cessna" /*&& model.Items.Count < 6*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //}
                break;

            case "Pilatus":
                company.SelectedValue = "Pilatus AirCraft";
                //        if (!IsPostBack)
                //      {
                foreach (PrivateJet n in Aerial.privatejet)
                {
                    if (n.made == "Pilatus AirCraft" /*&& model.Items.Count < 5*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //    }
                break;
            }
        }
コード例 #8
0
        public static void method(HttpServerUtility server, HttpRequest Request, DropDownList company, DropDownList model)
        {
            switch (server.UrlDecode(Request["company"]).ToString())
            {
            case "SEA-DOO":
                company.SelectedValue = "SEA-DOO";

                //  if (!IsPostBack)
                //{
                foreach (Yacht n in OverSea.yacht)
                {
                    if (n.made == "SEA-DOO" /*&& model.Items.Count < 6*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //}
                break;

            case "Kawasaki":
                company.SelectedValue = "Kawasaki";
                //        if (!IsPostBack)
                //      {
                foreach (Yacht n in OverSea.yacht)
                {
                    if (n.made == "Kawasaki" /*&& model.Items.Count < 5*/)
                    {
                        model.Items.Add(n.model);
                    }
                }
                //    }
                break;
            }
        }
コード例 #9
0
ファイル: ControllerBase.cs プロジェクト: nbl852003/iudico
 public static void LoadParametrs(TController c, NameValueCollection @params, HttpServerUtility server)
 {
     foreach (var pr in __ControllerParameters)
     {
         var v  = server.UrlDecode(@params[pr.Key]);
         var mt = pr.Value.MemberType;
         while (mt.IsGenericType && mt.GetGenericTypeDefinition() == typeof(Nullable <>))
         {
             mt = mt.GetGenericArguments()[0];
         }
         if (mt == typeof(int))
         {
             pr.Value[c] = int.Parse(v);
         }
         else if (mt == typeof(string))
         {
             pr.Value[c] = v;
         }
         else if (mt.IsEnum)
         {
             pr.Value[c] = mt.GetField(v).GetValue(null);
         }
         else
         {
             throw new InvalidOperationException();
         }
     }
 }
コード例 #10
0
        public NameValueCollection deformatNVP(string nvpStr)
        {
            HttpServerUtility   server = HttpContext.Current.Server;
            NameValueCollection result = new NameValueCollection();

            //nvpStr.Substring
            string[] v = nvpStr.Split('&');
            foreach (string value in v)
            {
                int    pos = value.IndexOf('='); //zero based
                string key = server.UrlDecode(value.Substring(0, pos));
                result[key] = server.UrlDecode(value.Substring(pos + 1));
            }

            return(result);
        }
コード例 #11
0
        private void RenameFileFolder()
        {
            HttpRequest       request = HttpContext.Current.Request;
            HttpServerUtility server  = HttpContext.Current.Server;
            string            str     = server.UrlDecode(request.Form["txtFolderName"]);
            string            path    = server.UrlDecode(request.Form["txtOldName"]);

            if (File.Exists(path))
            {
                try
                {
                    if (File.Exists(Path.GetDirectoryName(path) + @"\" + str))
                    {
                        this._Value = @"文件已存在时, 无法重命名或移动该文件 ";
                    }
                    else
                    {
                        File.Move(path, Path.GetDirectoryName(path) + @"\" + str);
                        this._Value = "重命名或移动文件成功, 新的文件名为: " + str;
                    }
                }
                catch
                {
                    this._Value = @"重命名或移动文件失败, 权限不足";
                }
            }
            else
            {
                try
                {
                    if (Directory.Exists(Path.GetDirectoryName(path) + @"\" + str))
                    {
                        this._Value = @"文件夹已存在时, 无法重命名或移动该文件夹 ";
                    }
                    else
                    {
                        Directory.Move(path, Path.GetDirectoryName(path) + @"\" + str);
                        this._Value = @"重命名或移动文件夹成功, 新的文件夹名为: " + str;
                    }
                }
                catch (Exception exception)
                {
                    this._Value = exception.Message;
                }
            }
        }
コード例 #12
0
        public void ProcessRequest(HttpContext context)
        {
            HttpServerUtility Server   = context.Server;
            HttpRequest       Request  = context.Request;
            HttpResponse      Response = context.Response;
            bool deletedFile           = false;

            //ATTEMPT TO STORE THE FILE IN ALL THE REPOSITORIES UNTIL ONE SUCCEEDS
            foreach (string tmpFolder in (from a in ((RepositorySettings)ConfigurationManager.GetSection("RepositorySettings")).RepositoryFolders where a.AccessMode.Contains("rw") select a.Path))
            {
                //FILE IS STORED IN THE COMBINATION OF THE LOCAL REPO FOLDER + FOLDER NAME PASSED IN
                string fileFolder = tmpFolder + Server.UrlDecode(Request.QueryString["folder"].Replace("/", "\\"));
                string fileName   = Path.Combine(fileFolder, Server.UrlDecode(Request.QueryString["filename"]));

                if (File.Exists(fileName))
                {
                    try
                    {
                        //TRY TO DELETE THE FILE
                        File.Delete(fileName);

                        //IF WE HAVE MADE IT THIS FAR THEN STOP PROCESSING
                        deletedFile = true;
                        break;
                    }
                    catch (Exception e)
                    {
                        Logging.WriteEntry(e.Message, e, new StackTrace());
                    }
                }
                else
                {
                    deletedFile = true;
                }
            }

            //CHECK TO SEE IF THE FILE WAS DELETED AND IF SO THEN RETURN SUCCESS OTHERWISE RETURN FAILURE
            if (deletedFile)
            {
                Response.Write("SUCCESS");
            }
            else
            {
                Response.Write("FAILURE");
            }
        }
コード例 #13
0
        public void ProcessRequest(HttpContext context)
        {
            HttpServerUtility Server   = context.Server;
            HttpRequest       Request  = context.Request;
            HttpResponse      Response = context.Response;
            bool savedFile             = false;

            //ATTEMPT TO STORE THE FILE IN ALL THE REPOSITORIES UNTIL ONE SUCCEEDS
            foreach (string tmpFolder in (from a in ((RepositorySettings)ConfigurationManager.GetSection("RepositorySettings")).RepositoryFolders where a.AccessMode.Contains("w") select a.Path))
            {
                //FILE IS STORED IN THE COMBINATION OF THE LOCAL REPO FOLDER + FOLDER NAME PASSED IN
                string fileFolder = tmpFolder + Server.UrlDecode(Request.QueryString["folder"].Replace("/", "\\"));
                string fileName   = Path.Combine(fileFolder, Server.UrlDecode(Request.QueryString["filename"]));

                //CREATE THE DIRECTORY AND ATTEMPT TO STORE THE FILE IF IT SUCCEEDS THEN BREAK AND RETURN TRUE OTHERWISE GO TO THE NEXT ONE
                try
                {
                    //CREATE THE DIRECTORY WHERE THE FILE IS TO BE STORED
                    Directory.CreateDirectory(fileFolder);

                    //SAVE THE FILE
                    Request.Files[0].SaveAs(fileName);

                    //STORE THE SUCCESS FOR RETURN VALUE LATER
                    savedFile = true;

                    //BREAK THE LOOP SO WE DO NOT STICK IT IN THE NEXT REPOSITORY
                    break;
                }
                catch (Exception e)
                {
                    //LOG THE REASON WE COULD NOT STORE THE FILE
                    Logging.WriteEntry(e.Message, e, new System.Diagnostics.StackTrace());
                }
            }

            //IF WE SAVED THE FILE THEN RETURN SUCCESS OTHERWISE RETURN FAILURE
            if (savedFile)
            {
                Response.Write("SUCCESS");
            }
            else
            {
                Response.Write("FAILURE");
            }
        }
コード例 #14
0
        private void Deserialize(string encryptedString)
        {
            HttpServerUtility server = HttpContext.Current.Server;

            // Decode the string back into a byte array.
            byte[] encryptedData = HexEncoding.GetBytes(encryptedString);

            // Decrypt the string.
            string decryptedString = EncryptionUtil.DecryptToString(encryptedData, crypt);

            // Split the string into values.
            string[] values = decryptedString.Split('&');
            foreach (string val in values)
            {
                string[] nameValuePair = val.Split('=');
                base.Add(server.UrlDecode(nameValuePair[0]), server.UrlDecode(nameValuePair[1]));
            }
        }
コード例 #15
0
        public string StartLogin(HttpSessionState session, HttpServerUtility Server)
        {
            String requestUrl = "https://www.google.com/accounts/OAuthGetRequestToken";

            string outParam;
            string normalUri;

            OAuthBase oAuth = new OAuthBase();

            Uri    url             = new Uri(requestUrl);
            string oauth_nonce     = oAuth.GenerateNonce();
            string oauth_timestamp = oAuth.GenerateTimeStamp();

            string signatureBase = oAuth.GenerateSignatureBase(url, oauth_consumer_key, "", "", "GET", oauth_timestamp, oauth_nonce, oauth_signature_method, out normalUri, out outParam);

            signatureBase += oAuth.UrlEncode("&scope=" + oAuth.UrlEncode(scope));

            HMACSHA1 hmacsha1        = new HMACSHA1(Encoding.ASCII.GetBytes(oAuth.UrlEncode(shared_secret) + "&"));
            string   oauth_signature = oAuth.GenerateSignatureUsingHash(signatureBase, hmacsha1);

            oauth_signature = oAuth.UrlEncode(oauth_signature);

            string     richiesta = requestUrl + "?" + outParam + "&oauth_signature=" + oauth_signature + "&scope=" + oAuth.UrlEncode(scope);
            WebRequest request   = WebRequest.Create(richiesta);

            request.Method = "GET";
            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (System.Net.WebException) { return(null); }
            StreamReader reader = new StreamReader(response.GetResponseStream());
            String       resp   = reader.ReadToEnd();

            reader.Close();
            response.Close();
            int    start            = resp.IndexOf('=') + 1;
            int    length           = resp.IndexOf('&') - start;
            string oauth_token_temp = resp.Substring(start, length);

            start = resp.IndexOf('=', start) + 1;
            string oauth_token_secret_temp = resp.Substring(start);

            richiesta  = "https://www.google.com/accounts/OAuthAuthorizeToken?";
            richiesta += "oauth_token=" + oauth_token_temp;
            richiesta += "&oauth_callback=" + oauth_callback;

            //session["GoogleOauthTokenSecret"] = Server.UrlDecode(oauth_token_secret_temp);
            oauth_token_secret = Server.UrlDecode(oauth_token_secret_temp);

            return(richiesta);
        }
コード例 #16
0
        protected IDictionary <string, string> GetApiResponseKvp(string response)
        {
            HttpServerUtility server = HttpContext.Current.Server;

            return((from item in response.Split('&')
                    let kvp = item.Split('=')
                              select new {
                Key = kvp[0],
                Value = server.UrlDecode(kvp[1])
            }).ToDictionary(i => i.Key, i => i.Value));
        }
コード例 #17
0
        public void ProcessRequest(HttpContext context)
        {
            HttpServerUtility Server   = context.Server;
            HttpRequest       Request  = context.Request;
            HttpResponse      Response = context.Response;
            bool sentFile = false;

            //ATTEMPT TO STORE THE FILE IN ALL THE REPOSITORIES UNTIL ONE SUCCEEDS
            foreach (string tmpFolder in (from a in ((RepositorySettings)ConfigurationManager.GetSection("RepositorySettings")).RepositoryFolders where a.AccessMode.Contains("r") select a.Path))
            {
                //FILE IS STORED IN THE COMBINATION OF THE LOCAL REPO FOLDER + FOLDER NAME PASSED IN
                string fileFolder = tmpFolder + Server.UrlDecode(Request.QueryString["folder"].Replace("/", "\\"));
                string fileName   = Path.Combine(fileFolder, Server.UrlDecode(Request.QueryString["filename"]));

                //IF THE FILE EXISTS THEN TRANSMIT IT BACK AND EXIT OTHERWISE WE WILL TRY THE OTHER REPOSITORIES
                if (File.Exists(fileName))
                {
                    try
                    {
                        Response.TransmitFile(fileName);
                        sentFile = true;

                        break;
                    }
                    catch (Exception e)
                    {
                        Logging.WriteEntry(e.Message, e, new StackTrace());
                    }
                }
            }

            //IF WE DID NOT SEND A FILE THEN THROW AN EXCEPTION
            if (!sentFile)
            {
                throw new Exception("File Not Found");
            }
        }
コード例 #18
0
        /// <summary>
        /// 重命名 移动 文件, 目录
        /// </summary>
        private void RenameFileFolder()
        {
            HttpRequest       Request = HttpContext.Current.Request;
            HttpServerUtility Server  = HttpContext.Current.Server;

            string newName = Request.Form["txtFolderName"];
            string oldName = Server.UrlDecode(Request.Form["txtOldName"]);

            if (File.Exists(oldName))
            {
                try
                {
                    if (File.Exists(Path.GetDirectoryName(oldName) + "\\" + newName))
                    {
                        this._Value = "文件已存在时, 无法重命名或移动该文件 ";
                    }
                    else
                    {
                        File.Move(oldName, Path.GetDirectoryName(oldName) + "\\" + newName);
                        this._Value = "重命名或移动文件成功, 新的文件名为: " + newName;
                    }
                }
                catch
                {
                    this._Value = "重命名或移动文件失败, 权限不足";
                }
            }
            else
            {
                try
                {
                    if (Directory.Exists(Path.GetDirectoryName(oldName) + "\\" + newName))
                    {
                        this._Value = "目录已存在时, 无法重命名或移动该目录 ";
                    }
                    else
                    {
                        Directory.Move(oldName, Path.GetDirectoryName(oldName) + "\\" + newName);
                        this._Value = "重命名或移动目录成功, 新的目录名为: " + newName;
                    }
                }
                catch (Exception ex)
                {
                    // this._Value = "重命名或移动目录失败, 权限不足";
                    this._Value = ex.Message;
                }
            }
        }
コード例 #19
0
        /// <summary>
        /// 设置权限树
        /// </summary>
        public void SetPermissionTree()
        {
            int    roleId    = Convert.ToInt32(Server.UrlDecode(Request["RoleId"].ToString()));
            string resultStr = string.Empty;

            List <string> lsP = new List <string>();

            lsP = PermissionAccess.GetInstance().GetParentPermission();
            //此处省略得到数据列表的代码
            resultStr  = "";
            resultStr += "[";
            foreach (string item in lsP)
            {
                resultStr += "{";

                List <PermissionEntity> lsC = new List <PermissionEntity>();
                lsC = PermissionAccess.GetInstance().GetChildPermission(item);
                //如果某变电站下有线路
                if (lsC.Count > 0)
                {
                    resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"state\": \"closed\"", item, item);
                    resultStr += ",\"children\":[";

                    for (int i = 0; i < lsC.Count; i++)
                    {
                        resultStr += "{";
                        resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\",\"checked\":{2} ", lsC[i].PermissionId, lsC[i].OperationName, RolePermissionAccess.GetInstance().IsPermissionOn(roleId, lsC[i].PermissionId) == null ? "false" : "true");
                        resultStr += "},";
                    }
                    resultStr  = resultStr.Substring(0, resultStr.Length - 1);
                    resultStr += "]";
                }
                else
                {
                    resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\" ", item, item);
                }
                resultStr += "},";
            }

            resultStr  = resultStr.Substring(0, resultStr.Length - 1);
            resultStr += "]";

            Response.Write(resultStr);
        }
コード例 #20
0
        public IHttpActionResult CreateDirectory([FromUri()] string currentDirectoryString, [FromUri()] int functionSeqId, [FromUri()] string newDirectory)
        {
            string mRetVal = "Unable to create directory";

            if (String.IsNullOrEmpty(currentDirectoryString) || String.IsNullOrEmpty(newDirectory))
            {
                mRetVal = "All parameters must be passed!";
                ArgumentException ex   = new ArgumentException(mRetVal);
                Logger            mLog = Logger.Instance();
                mLog.Error(mRetVal);
                throw (ex);
            }
            HttpServerUtility mServer           = HttpContext.Current.Server;
            MDirectoryProfile mDirectoryProfile = DirectoryUtility.GetProfile(functionSeqId);
            String            mCurrentDirectory = mDirectoryProfile.Directory;

            if (currentDirectoryString.Length > 0)
            {
                mCurrentDirectory += @"\" + currentDirectoryString;
            }
            mRetVal = FileUtility.CreateDirectory(mServer.UrlDecode(mCurrentDirectory), mServer.UrlDecode(newDirectory), mDirectoryProfile);
            return(this.Ok(mRetVal));
        }
コード例 #21
0
 public string UrlDecode(string s)
 {
     return(_server.UrlDecode(s));
 }
コード例 #22
0
    public static string SaveChanges(string workItemType_ID, string rows)
    {
        Dictionary <string, string> result = new Dictionary <string, string>()
        {
            { "saved", "0" }
            , { "failed", "0" }
            , { "savedIds", "" }
            , { "failedIds", "" }
            , { "error", "" }
        };
        bool   exists = false, saved = false;
        int    savedQty = 0, failedQty = 0;
        string ids = string.Empty, failedIds = string.Empty, errorMsg = string.Empty, tempMsg = string.Empty;

        try
        {
            DataTable dtjson = (DataTable)JsonConvert.DeserializeObject(rows, (typeof(DataTable)));
            if (dtjson.Rows.Count == 0)
            {
                errorMsg = "Unable to save. An invalid list of changes was provided.";
                saved    = false;
            }
            else
            {
                int    id = 0, workItemTypeID = 0, resourceTypeID = 0, archive = 0;   //, ALLOCATIONGROUPID = 0;
                bool   duplicate   = false;
                string description = string.Empty;

                HttpServerUtility server = HttpContext.Current.Server;
                //save
                foreach (DataRow dr in dtjson.Rows)
                {
                    id          = workItemTypeID = resourceTypeID = 0;
                    archive     = 0;
                    description = string.Empty;
                    archive     = 0;
                    duplicate   = false;

                    tempMsg = string.Empty;
                    int.TryParse(dr["WorkActivity_WTS_RESOURCE_TYPEID"].ToString(), out id);
                    int.TryParse(workItemType_ID, out workItemTypeID);
                    int.TryParse(dr["WTS_RESOURCE_TYPE"].ToString(), out resourceTypeID);
                    description = server.UrlDecode(dr["DESCRIPTION"].ToString());
                    int.TryParse(dr["ARCHIVE"].ToString(), out archive);

                    if (resourceTypeID == 0)
                    {
                        tempMsg = "You must specify a Resource Type.";
                        saved   = false;
                    }
                    else
                    {
                        if (id == 0)
                        {
                            exists = false;
                            saved  = MasterData.WORKITEMTYPE_ResourceType_Add(WORKITEMTYPEID: workItemTypeID
                                                                              , ResourceTypeID: resourceTypeID
                                                                              , exists: out exists
                                                                              , newID: out id
                                                                              , errorMsg: out tempMsg);
                            if (exists)
                            {
                                saved   = false;
                                tempMsg = string.Format("{0}{1}{2}", tempMsg, tempMsg.Length > 0 ? Environment.NewLine : "", "Cannot add duplicate Work Activity - Resource Type record.");
                            }
                        }
                        else
                        {
                            saved = MasterData.WORKITEMTYPE_ResourceType_Update(WorkActivity_WTS_RESOURCE_TYPEID: id
                                                                                , WORKITEMTYPEID: workItemTypeID
                                                                                , ResourceTypeID: resourceTypeID
                                                                                , archive: (archive == 1)
                                                                                , duplicate: out duplicate
                                                                                , errorMsg: out tempMsg);
                        }
                    }

                    if (saved)
                    {
                        ids      += string.Format("{0}{1}", ids.Length > 0 ? "," : "", id.ToString());
                        savedQty += 1;
                    }
                    else
                    {
                        failedQty += 1;
                    }

                    if (tempMsg.Length > 0)
                    {
                        errorMsg = string.Format("{0}{1}{2}", errorMsg, errorMsg.Length > 0 ? Environment.NewLine : "", tempMsg);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            saved    = false;
            errorMsg = ex.Message;
            LogUtility.LogException(ex);
        }

        result["savedIds"]  = ids;
        result["failedIds"] = failedIds;
        result["saved"]     = savedQty.ToString();
        result["failed"]    = failedQty.ToString();
        result["error"]     = errorMsg;

        return(JsonConvert.SerializeObject(result, Formatting.None));
    }
コード例 #23
0
 public override string UrlDecode(string s)
 {
     return(_httpServerUtility.UrlDecode(s));
 }
コード例 #24
0
 /// <summary>
 /// URL decodes a string and returns the decoded string.
 /// </summary>
 /// <param name="content">The text to URL decode.</param>
 /// <returns>The URL decoded text.</returns>
 public String UrlDecode(String content)
 {
     return(server.UrlDecode(content));
 }
コード例 #25
0
    public static string SaveChanges(string rows)
    {
        Dictionary <string, string> result = new Dictionary <string, string>()
        {
            { "saved", "" }, { "ids", "" }, { "error", "" }
        };
        bool   exists = false, saved = false;
        string ids = string.Empty, errorMsg = string.Empty, tempMsg = string.Empty;

        try
        {
            DataTable dtjson = (DataTable)JsonConvert.DeserializeObject(rows, (typeof(DataTable)));
            if (dtjson.Rows.Count == 0)
            {
                errorMsg = "Unable to save. An invalid list of changes was provided.";
                saved    = false;
            }

            int    id = 0, defaultSelection = 0, sortOrder = 0, statusId = 0, archive = 0;
            string productVersion = string.Empty, description = string.Empty, narrative = string.Empty, startDate = string.Empty, endDate = string.Empty;

            HttpServerUtility server = HttpContext.Current.Server;
            //save
            foreach (DataRow dr in dtjson.Rows)
            {
                id = 0;
                defaultSelection = 0;
                sortOrder        = 0;
                statusId         = 0;
                productVersion   = string.Empty;
                description      = string.Empty;
                narrative        = string.Empty;
                startDate        = string.Empty;
                endDate          = string.Empty;
                archive          = 0;

                tempMsg = string.Empty;
                int.TryParse(dr["ProductVersionID"].ToString(), out id);
                productVersion = server.UrlDecode(dr["ProductVersion"].ToString());
                description    = server.UrlDecode(dr["DESCRIPTION"].ToString());
                narrative      = server.UrlDecode(dr["Narrative"].ToString());
                startDate      = server.UrlDecode(dr["StartDate"].ToString());
                endDate        = server.UrlDecode(dr["EndDate"].ToString());
                int.TryParse(dr["DefaultSelection"].ToString(), out defaultSelection);
                int.TryParse(dr["SORT_ORDER"].ToString(), out sortOrder);
                int.TryParse(dr["STATUS"].ToString(), out statusId);
                int.TryParse(dr["ARCHIVE"].ToString(), out archive);

                if (string.IsNullOrWhiteSpace(productVersion))
                {
                    tempMsg = "You must specify a Product Version.";
                    saved   = false;
                }
                else if (statusId == 0)
                {
                    tempMsg = "You must specify a value for Status.";
                    saved   = false;
                }
                else
                {
                    if (id == 0)
                    {
                        exists = false;
                        saved  = MasterData.ProductVersion_Add(productVersion, description, narrative, startDate, endDate, (defaultSelection == 1), sortOrder, statusId, (archive == 1), out exists, out id, out tempMsg);
                        if (exists)
                        {
                            saved   = false;
                            tempMsg = string.Format("{0}{1}{2}", tempMsg, tempMsg.Length > 0 ? Environment.NewLine : "", "Cannot add duplicate Product Version record [" + productVersion + "].");
                        }
                    }
                    else
                    {
                        saved = MasterData.ProductVersion_Update(id, productVersion, description, narrative, startDate, endDate, (defaultSelection == 1), sortOrder, statusId, (archive == 1), out tempMsg);
                    }
                }

                if (saved)
                {
                    ids += string.Format("{0}{1}", ids.Length > 0 ? "," : "", id.ToString());
                }

                if (tempMsg.Length > 0)
                {
                    errorMsg = string.Format("{0}{1}{2}", errorMsg, errorMsg.Length > 0 ? Environment.NewLine : "", tempMsg);
                }
            }
        }
        catch (Exception ex)
        {
            saved    = false;
            errorMsg = ex.Message;
            LogUtility.LogException(ex);
        }

        result["ids"]   = ids;
        result["saved"] = saved.ToString();
        result["error"] = errorMsg;

        return(JsonConvert.SerializeObject(result, Formatting.None));
    }
コード例 #26
0
    public static string SaveChanges(string rows, int systemSuiteID = 0)
    {
        Dictionary <string, string> result = new Dictionary <string, string>()
        {
            { "saved", "" }, { "ids", "" }, { "error", "" }
        };
        bool   exists = false, saved = false;
        string ids = string.Empty, errorMsg = string.Empty, tempMsg = string.Empty;

        try
        {
            DataTable dtjson = (DataTable)JsonConvert.DeserializeObject(rows, (typeof(DataTable)));
            if (dtjson.Rows.Count == 0)
            {
                errorMsg = "Unable to save. An invalid list of changes was provided.";
                saved    = false;
            }

            int    id = 0, proposedPriorityRank = 0, approvedPriorityRank = 0, archive = 0;
            string WorkArea = string.Empty, description = string.Empty;

            HttpServerUtility server = HttpContext.Current.Server;
            //save
            foreach (DataRow dr in dtjson.Rows)
            {
                id = 0;
                proposedPriorityRank = 0;
                approvedPriorityRank = 0;
                WorkArea             = string.Empty;
                description          = string.Empty;
                archive = 0;

                tempMsg = string.Empty;
                int.TryParse(dr["WorkAreaID"].ToString(), out id);
                WorkArea    = server.UrlDecode(dr["WorkArea"].ToString());
                description = server.UrlDecode(dr["Description"].ToString());
                int.TryParse(dr["ProposedPriorityRank"].ToString(), out proposedPriorityRank);
                int.TryParse(dr["ActualPriorityRank"].ToString(), out approvedPriorityRank);
                int.TryParse(dr["ARCHIVE"].ToString(), out archive);

                if (string.IsNullOrWhiteSpace(WorkArea))
                {
                    tempMsg = "You must specify a value for Allocation.";
                    saved   = false;
                }
                else
                {
                    if (id == 0)
                    {
                        exists = false;
                        saved  = MasterData.WorkArea_Add(WorkArea: WorkArea, description: description, proposedPriorityRank: proposedPriorityRank, exists: out exists, newID: out id, errorMsg: out tempMsg);
                        if (exists)
                        {
                            saved   = false;
                            tempMsg = string.Format("{0}{1}{2}", tempMsg, tempMsg.Length > 0 ? Environment.NewLine : "", "Cannot add duplicate Allocation record [" + WorkArea + "].");
                        }
                        else
                        {
                            if (systemSuiteID > 0)
                            {
                                DataTable dtSystem = MasterData.SystemList_Get(includeArchive: true);
                                dtSystem.DefaultView.RowFilter = "(WTS_SystemSuiteID = " + systemSuiteID + "OR WTS_SystemID = 0) AND ARCHIVE = 0";
                                dtSystem = dtSystem.DefaultView.ToTable();
                                foreach (DataRow drSystem in dtSystem.Rows)
                                {
                                    int systemID = 0, waSystemID = 0;
                                    int.TryParse(drSystem["WTS_SystemID"].ToString(), out systemID);
                                    if (systemID > 0)
                                    {
                                        MasterData.WorkArea_System_Add(workAreaID: id, systemID: systemID, description: "", proposedPriority: proposedPriorityRank, approvedPriority: 0, cv: "0", exists: out exists, newID: out waSystemID, errorMsg: out tempMsg);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        saved = MasterData.WorkArea_Update(WorkAreaID: id, WorkArea: WorkArea, description: description, proposedPriorityRank: proposedPriorityRank, archive: (archive == 1), errorMsg: out tempMsg);
                    }
                }

                if (saved)
                {
                    ids += string.Format("{0}{1}", ids.Length > 0 ? "," : "", id.ToString());
                }

                if (tempMsg.Length > 0)
                {
                    errorMsg = string.Format("{0}{1}{2}", errorMsg, errorMsg.Length > 0 ? Environment.NewLine : "", tempMsg);
                }
            }
        }
        catch (Exception ex)
        {
            saved    = false;
            errorMsg = ex.Message;
            LogUtility.LogException(ex);
        }

        result["ids"]   = ids;
        result["saved"] = saved.ToString();
        result["error"] = errorMsg;

        WTS.Caching.WTSCache.Instance.ClearCache(WTSCacheType.WORK_AREA);

        return(JsonConvert.SerializeObject(result, Formatting.None));
    }
コード例 #27
0
    public SearchEngineMng(string currentUserIp,
                           HttpContext context,
                           string action)
    {
        _currentUserIp = currentUserIp;
        this.context   = context;
        currentR       = context.Request;
        currentS       = context.Server;
        mngInfo        = new TimeZoneManager(currentUserIp);

        string sLangId = context.Request.QueryString["li"];

        if (string.IsNullOrEmpty(sLangId))
        {
            isValid      = false;
            errorMessage = "You forgot langid (querystring li)";
        }

        // Convert langid querystring to int32
        if (!Int32.TryParse(sLangId, out currentLangId))
        {
            isValid      = false;
            errorMessage = "Problem with converting langauge ID (querystring li)";
        }

        if (context.Session["usi"] == null || action == "1")
        {
            // Create user default information
            usi.UserID        = (Guid)ANOProfile.GetCookieValues(currentUserIp, context).UserID;
            usi.UserIpAddress = currentUserIp;

            #region Set ints data (Get data by QueryStrings)

            var dataConvertToInts = new
            {
                clanSkillID       = (string)currentR.QueryString["cs"],
                clanContinentID   = (string)currentR.QueryString["cct"],
                clanCountryID     = (string)currentR.QueryString["cc"],
                searchContinentID = (string)currentR.QueryString["sct"],
                searchCountryID   = (string)currentR.QueryString["sc"],
                searchGameID      = (string)currentR.QueryString["sg"],
                searchGameModeID  = (string)currentR.QueryString["sgt"],
                searchXvs         = (string)currentR.QueryString["sxv"],
                searchvsX         = (string)currentR.QueryString["svx"]
            }.ToAnonymousObjectCollection();

            int MaxIntValue = int.MaxValue;
            var intdata     = new
            {
                clanSkillID       = (int?)null,
                clanContinentID   = (int)MaxIntValue,
                clanCountryID     = (int)MaxIntValue,
                searchContinentID = (int)MaxIntValue,
                searchCountryID   = (int?)null,
                searchGameID      = (int)MaxIntValue,
                searchGameModeID  = (int?)null,
                searchXvs         = (int?)null,
                searchvsX         = (int?)null,
                searchYearFrom    = (int)MaxIntValue,
                searchDayFrom     = (int)MaxIntValue,
                searchMonthFrom   = (int)MaxIntValue,
                searchHourFrom    = (int)MaxIntValue,
                searchMinutesFrom = (int)MaxIntValue,
            }.ToAnonymousObjectCollection();

            #endregion

            #region validate and convert properties to ints

            for (int i = 0; i < dataConvertToInts.Count; i++)
            {
                AnonymousObject o = dataConvertToInts.GetAnonymousObject(i);

                if (!string.IsNullOrEmpty(o.GetValue <string>()))
                {
                    int result;
                    if (int.TryParse(o.GetValue <string>(), out result))
                    {
                        intdata.GetAnonymousObject(o.KeyName).SetValue(result);
                    }
                }

                if (intdata.GetAnonymousObject(o.KeyName).GetValue_UnknownObject() != null
                    &&
                    Convert.ToInt32(intdata.GetAnonymousObject(o.KeyName).GetValue_UnknownObject()) == MaxIntValue)
                {
                    isValid      = false;
                    errorMessage = "'" + o.KeyName +
                                   "' much be more than empty";
                }
            }

            #endregion

            #region Set strings data (convert to HtmlEncode strings)

            var stringData = new
            {
                ClanName  = (string)currentS.HtmlEncode(currentS.UrlDecode(currentR.QueryString["cn"])),
                SearchMap = (string)currentS.HtmlEncode(currentS.UrlDecode(currentR.QueryString["sm"])),
            };

            #endregion

            #region Set datetime data (Replace + and . (This chars is used to avoid problems))

            if (string.IsNullOrEmpty(currentR.QueryString["sfd"]))
            {
                isValid      = false;
                errorMessage = "'SearchMatchStart' much be more than empty";
            }
            else
            {
                var datetimeData = new
                {
                    SearchMatchStart = (DateTime)DateTime.ParseExact(currentS.UrlDecode(currentR.QueryString["sfd"]), "dd-MM-yyyy HH:mm:ss", new DateTimeFormatInfo())
                };

                #endregion

                // Edit/Create user search information
                usi.ClanName          = stringData.ClanName;
                usi.ClanSkillID       = intdata.GetAnonymousObject("clanSkillID").GetValue <int?>();
                usi.ClanContinentID   = intdata.GetAnonymousObject("clanContinentID").GetValue <int>();
                usi.ClanCountryID     = intdata.GetAnonymousObject("clanCountryID").GetValue <int>();
                usi.SearchContinentID = intdata.GetAnonymousObject("searchContinentID").GetValue <int>();
                usi.SearchCountryID   = intdata.GetAnonymousObject("searchCountryID").GetValue <int?>();
                usi.SearchGameID      = intdata.GetAnonymousObject("searchGameID").GetValue <int>();
                usi.SearchGameModeID  = intdata.GetAnonymousObject("searchGameModeID").GetValue <int?>();
                usi.SearchMap         = stringData.SearchMap;
                usi.SearchXvs         = intdata.GetAnonymousObject("searchXvs").GetValue <int>();
                usi.SearchvsX         = intdata.GetAnonymousObject("searchvsX").GetValue <int>();
                usi.SearchMatchStart  = new TimeZoneManager(currentUserIp).ConvertDateTimeToUtc(datetimeData.SearchMatchStart);

                userOption             = SearchWar.SearchEngine.SearchEngine.UserSearchOption.CreateUserSearch;
                context.Session["usi"] = usi;
            }
        }
        else
        {
            usi = (UserSearchInfo)context.Session["usi"];
        }

        if (isValid == true)
        {
            LangaugeSystem ls      = new LangaugeSystem();
            string         getLang = ls.GetLang(Convert.ToInt32(sLangId)).LangShortname;
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(getLang);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(getLang);
        }
    }
コード例 #28
0
    public static string SaveChanges(string rows)
    {
        Dictionary <string, string> result = new Dictionary <string, string>()
        {
            { "saved", "" }, { "ids", "" }, { "error", "" }
        };
        bool   exists = false, saved = false, duplicate = false;
        string ids = string.Empty, errorMsg = string.Empty, tempMsg = string.Empty;

        try
        {
            DataTable dtjson = (DataTable)JsonConvert.DeserializeObject(rows, (typeof(DataTable)));
            if (dtjson.Rows.Count == 0)
            {
                errorMsg = "Unable to save. An invalid list of changes was provided.";
                saved    = false;
            }

            int    id = 0, sortOrder = 0, archive = 0;
            string effortArea = string.Empty, description = string.Empty;

            HttpServerUtility server = HttpContext.Current.Server;
            //save
            foreach (DataRow dr in dtjson.Rows)
            {
                id          = 0;
                sortOrder   = 0;
                effortArea  = string.Empty;
                description = string.Empty;
                archive     = 0;

                tempMsg = string.Empty;
                int.TryParse(dr["EffortAreaID"].ToString(), out id);
                effortArea  = server.UrlDecode(dr["EffortArea"].ToString());
                description = server.UrlDecode(dr["Description"].ToString());
                int.TryParse(dr["SORT_ORDER"].ToString(), out sortOrder);
                int.TryParse(dr["ARCHIVE"].ToString(), out archive);

                if (string.IsNullOrWhiteSpace(effortArea))
                {
                    tempMsg = "You must specify a value for Area of Effort.";
                    saved   = false;
                }
                else
                {
                    if (id == 0)
                    {
                        exists = false;
                        saved  = MasterData.EffortArea_Add(effortArea: effortArea, description: description, sortOrder: sortOrder, archive: (archive == 1), exists: out exists, newID: out id, errorMsg: out tempMsg);
                        if (exists)
                        {
                            saved   = false;
                            tempMsg = string.Format("{0}{1}{2}", tempMsg, tempMsg.Length > 0 ? Environment.NewLine : "", "Cannot add duplicate Area of Effort record [" + effortArea + "].");
                        }
                    }
                    else
                    {
                        saved = MasterData.EffortArea_Update(effortAreaID: id, effortArea: effortArea, description: description, sortOrder: sortOrder, archive: (archive == 1), duplicate: out duplicate, errorMsg: out tempMsg);
                    }
                }

                if (saved)
                {
                    ids += string.Format("{0}{1}", ids.Length > 0 ? "," : "", id.ToString());
                }

                if (tempMsg.Length > 0)
                {
                    errorMsg = string.Format("{0}{1}{2}", errorMsg, errorMsg.Length > 0 ? Environment.NewLine : "", tempMsg);
                }
            }
        }
        catch (Exception ex)
        {
            LogUtility.LogException(ex);
            saved    = false;
            errorMsg = ex.Message;
        }

        result["saved"] = saved.ToString();
        result["error"] = errorMsg;

        return(JsonConvert.SerializeObject(result, Formatting.None));
    }
コード例 #29
0
        internal override void RewriteUrl(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            HttpServerUtility server        = app.Server;
            HttpRequest       request       = app.Request;
            HttpResponse      response      = app.Response;
            HttpContext       context       = app.Context;
            string            requestedPath = app.Request.Url.AbsoluteUri;

            if (RewriterUtils.OmitFromRewriteProcessing(request.Url.LocalPath))
            {
                return;
            }

            // 'Carry out first time initialization tasks
            Initialize.Init(app);
            if (!Initialize.ProcessHttpModule(request, false, false))
            {
                return;
            }

            // URL validation
            // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server
            // the application should always use the exact relative location of the resource it is requesting
            var strURL             = request.Url.AbsolutePath;
            var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.RawUrl)) ?? string.Empty;

            if (Globals.FileEscapingRegex.Match(strURL).Success || Globals.FileEscapingRegex.Match(strDoubleDecodeURL).Success)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
            }

            try
            {
                // fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459
                if (request.Path.IndexOf("\\", StringComparison.Ordinal) >= 0 || Path.GetFullPath(request.PhysicalPath) != request.PhysicalPath)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
                }
            }
            catch (Exception exc)
            {
                // DNN 5479
                // request.physicalPath throws an exception when the path of the request exceeds 248 chars.
                // example to test: http://localhost/dotnetnuke_2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/default.aspx
                Logger.Error(exc);
            }

            string domainName;

            this.RewriteUrl(app, out domainName);

            // blank DomainName indicates RewriteUrl couldn't locate a current portal
            // reprocess url for portal alias if auto add is an option
            if (domainName == string.Empty && CanAutoAddPortalAlias())
            {
                domainName = Globals.GetDomainName(app.Request, true);
            }

            // from this point on we are dealing with a "standard" querystring ( ie. http://www.domain.com/default.aspx?tabid=## )
            // if the portal/url was succesfully identified
            int             tabId           = Null.NullInteger;
            int             portalId        = Null.NullInteger;
            string          portalAlias     = null;
            PortalAliasInfo portalAliasInfo = null;
            bool            parsingError    = false;

            // get TabId from querystring ( this is mandatory for maintaining portal context for child portals )
            if (!string.IsNullOrEmpty(request.QueryString["tabid"]))
            {
                if (!int.TryParse(request.QueryString["tabid"], out tabId))
                {
                    tabId        = Null.NullInteger;
                    parsingError = true;
                }
            }

            // get PortalId from querystring ( this is used for host menu options as well as child portal navigation )
            if (!string.IsNullOrEmpty(request.QueryString["portalid"]))
            {
                if (!int.TryParse(request.QueryString["portalid"], out portalId))
                {
                    portalId     = Null.NullInteger;
                    parsingError = true;
                }
            }

            if (parsingError)
            {
                // The tabId or PortalId are incorrectly formatted (potential DOS)
                DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
            }

            try
            {
                // alias parameter can be used to switch portals
                if (request.QueryString["alias"] != null)
                {
                    // check if the alias is valid
                    string childAlias = request.QueryString["alias"];
                    if (!Globals.UsePortNumber())
                    {
                        childAlias = childAlias.Replace(":" + request.Url.Port, string.Empty);
                    }

                    if (PortalAliasController.Instance.GetPortalAlias(childAlias) != null)
                    {
                        // check if the domain name contains the alias
                        if (childAlias.IndexOf(domainName, StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            // redirect to the url defined in the alias
                            response.Redirect(Globals.GetPortalDomainName(childAlias, request, true), true);
                        }
                        else // the alias is the same as the current domain
                        {
                            portalAlias = childAlias;
                        }
                    }
                }

                // PortalId identifies a portal when set
                if (portalAlias == null)
                {
                    if (portalId != Null.NullInteger)
                    {
                        portalAlias = PortalAliasController.GetPortalAliasByPortal(portalId, domainName);
                    }
                }

                // TabId uniquely identifies a Portal
                if (portalAlias == null)
                {
                    if (tabId != Null.NullInteger)
                    {
                        // get the alias from the tabid, but only if it is for a tab in that domain
                        portalAlias = PortalAliasController.GetPortalAliasByTab(tabId, domainName);
                        if (string.IsNullOrEmpty(portalAlias))
                        {
                            // if the TabId is not for the correct domain
                            // see if the correct domain can be found and redirect it
                            portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(domainName);
                            if (portalAliasInfo != null && !request.Url.LocalPath.ToLowerInvariant().EndsWith("/linkclick.aspx"))
                            {
                                if (app.Request.Url.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    strURL = "https://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty);
                                }
                                else
                                {
                                    strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty);
                                }

                                if (strURL.IndexOf(domainName, StringComparison.InvariantCultureIgnoreCase) == -1)
                                {
                                    strURL += app.Request.Url.PathAndQuery;
                                }

                                response.Redirect(strURL, true);
                            }
                        }
                    }
                }

                // else use the domain name
                if (string.IsNullOrEmpty(portalAlias))
                {
                    portalAlias = domainName;
                }

                // using the DomainName above will find that alias that is the domainname portion of the Url
                // ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url
                portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias);
                if (portalAliasInfo != null)
                {
                    portalId = portalAliasInfo.PortalID;
                }

                // if the portalid is not known
                if (portalId == Null.NullInteger)
                {
                    bool autoAddPortalAlias = CanAutoAddPortalAlias();

                    if (!autoAddPortalAlias && !request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // allows requests for aspx pages in custom folder locations to be processed
                        return;
                    }

                    if (autoAddPortalAlias)
                    {
                        AutoAddAlias(context);
                    }
                }
            }
            catch (ThreadAbortException exc)
            {
                // Do nothing if Thread is being aborted - there are two response.redirect calls in the Try block
                Logger.Debug(exc);
            }
            catch (Exception ex)
            {
                // 500 Error - Redirect to ErrorPage
                Logger.Error(ex);

                strURL = "~/ErrorPage.aspx?status=500&error=" + server.UrlEncode(ex.Message);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Server.Transfer(strURL);
            }

            if (portalId != -1)
            {
                // load the PortalSettings into current context
                var portalSettings = new PortalSettings(tabId, portalAliasInfo);
                app.Context.Items.Add("PortalSettings", portalSettings);

                // load PortalSettings and HostSettings dictionaries into current context
                // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way
                app.Context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalId));
                app.Context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary());

                if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect &&
                    portalAliasInfo != null && !portalAliasInfo.IsPrimary &&
                    !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias))    // don't redirect if no primary alias is defined
                {
                    // Permanently Redirect
                    response.StatusCode = 301;

                    var redirectAlias = Globals.AddHTTP(portalSettings.DefaultPortalAlias);
                    var checkAlias    = Globals.AddHTTP(portalAliasInfo.HTTPAlias);
                    var redirectUrl   = string.Concat(redirectAlias, request.RawUrl);
                    if (redirectUrl.StartsWith(checkAlias, StringComparison.InvariantCultureIgnoreCase))
                    {
                        redirectUrl = string.Concat(redirectAlias, redirectUrl.Substring(checkAlias.Length));
                    }

                    response.AppendHeader("Location", redirectUrl);
                }

                // manage page URL redirects - that reach here because they bypass the built-in navigation
                // ie Spiders, saved favorites, hand-crafted urls etc
                if (!string.IsNullOrEmpty(portalSettings.ActiveTab.Url) && request.QueryString["ctl"] == null &&
                    request.QueryString["fileticket"] == null)
                {
                    // Target Url
                    string redirectUrl = portalSettings.ActiveTab.FullUrl;
                    if (portalSettings.ActiveTab.PermanentRedirect)
                    {
                        // Permanently Redirect
                        response.StatusCode = 301;
                        response.AppendHeader("Location", redirectUrl);
                    }
                    else
                    {
                        // Normal Redirect
                        response.Redirect(redirectUrl, true);
                    }
                }

                // manage secure connections
                if (request.Url.AbsolutePath.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase))
                {
                    // request is for a standard page
                    strURL = string.Empty;

                    // if SSL is enabled
                    if (portalSettings.SSLEnabled)
                    {
                        // if page is secure and connection is not secure orelse ssloffload is enabled and server value exists
                        if ((portalSettings.ActiveTab.IsSecure && !request.IsSecureConnection) &&
                            (UrlUtils.IsSslOffloadEnabled(request) == false))
                        {
                            // switch to secure connection
                            strURL = requestedPath.Replace("http://", "https://");
                            strURL = this.FormatDomain(strURL, portalSettings.STDURL, portalSettings.SSLURL);
                        }
                    }

                    // if SSL is enforced
                    if (portalSettings.SSLEnforced)
                    {
                        // if page is not secure and connection is secure
                        if (!portalSettings.ActiveTab.IsSecure && request.IsSecureConnection)
                        {
                            // check if connection has already been forced to secure orelse ssloffload is disabled
                            if (request.QueryString["ssl"] == null)
                            {
                                strURL = requestedPath.Replace("https://", "http://");
                                strURL = this.FormatDomain(strURL, portalSettings.SSLURL, portalSettings.STDURL);
                            }
                        }
                    }

                    // if a protocol switch is necessary
                    if (!string.IsNullOrEmpty(strURL))
                    {
                        if (strURL.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                        {
                            // redirect to secure connection
                            response.RedirectPermanent(strURL);
                        }
                        else

                        // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning
                        {
                            response.Clear();

                            // add a refresh header to the response
                            response.AddHeader("Refresh", "0;URL=" + strURL);

                            // add the clientside javascript redirection script
                            response.Write("<html><head><title></title>");
                            response.Write("<!-- <script language=\"javascript\">window.location.replace(\"" + strURL +
                                           "\")</script> -->");
                            response.Write("</head><body></body></html>");

                            // send the response
                            response.End();
                        }
                    }
                }
            }
            else
            {
                // alias does not exist in database
                // and all attempts to find another have failed
                // this should only happen if the HostPortal does not have any aliases
                // 404 Error - Redirect to ErrorPage
                strURL = "~/ErrorPage.aspx?status=404&error=" + domainName;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Server.Transfer(strURL);
            }

            if (app.Context.Items["FirstRequest"] != null)
            {
                app.Context.Items.Remove("FirstRequest");

                // Process any messages in the EventQueue for the Application_Start_FirstRequest event
                EventQueueController.ProcessMessages("Application_Start_FirstRequest");
            }
        }
コード例 #30
0
    public static string SaveChanges(string rows)
    {
        Dictionary <string, string> result = new Dictionary <string, string>()
        {
            { "saved", "0" }
            , { "failed", "0" }
            , { "savedIds", "" }
            , { "failedIds", "" }
            , { "error", "" }
        };
        bool   exists = false, saved = false, duplicate = false;
        int    savedQty = 0, failedQty = 0;
        string ids = string.Empty, failedIds = string.Empty, errorMsg = string.Empty, tempMsg = string.Empty;

        try
        {
            DataTable dtjson = (DataTable)JsonConvert.DeserializeObject(rows, (typeof(DataTable)));
            if (dtjson == null || dtjson.Rows.Count == 0)
            {
                errorMsg = "Unable to save. No list of changes was provided.";
            }
            else
            {
                int    id = 0;
                string name = string.Empty, description = string.Empty, notes = string.Empty;

                HttpServerUtility server = HttpContext.Current.Server;
                //save
                foreach (DataRow dr in dtjson.Rows)
                {
                    id          = 0;
                    name        = string.Empty;
                    description = string.Empty;
                    notes       = string.Empty;

                    tempMsg = string.Empty;
                    int.TryParse(dr["AOREstimation_AORAssocID"].ToString(), out id);
                    notes = server.UrlDecode(dr["Notes"].ToString());

                    saved = AOR.AOREstimation_Assoc_Update(
                        AOREstimation_AORAssocID: id, Notes: notes, duplicate: out duplicate, errorMsg: out tempMsg);

                    if (saved)
                    {
                        savedQty += 1;
                        ids      += string.Format("{0}{1}", ids.Length > 0 ? "," : "", id.ToString());
                    }

                    else
                    {
                        failedQty += 1;
                        failedIds += string.Format("{0}{1}", failedIds.Length > 0 ? "," : "", failedIds.ToString());
                    }
                    if (tempMsg.Length > 0)
                    {
                        errorMsg = string.Format("{0}{1}{2}", errorMsg, errorMsg.Length > 0 ? Environment.NewLine : "", tempMsg);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogUtility.LogException(ex);
            saved    = false;
            errorMsg = ex.Message;
        }

        result["savedIds"]  = ids;
        result["failedIds"] = failedIds;
        result["saved"]     = savedQty.ToString();
        result["failed"]    = failedQty.ToString();
        result["error"]     = errorMsg;

        return(JsonConvert.SerializeObject(result, Formatting.None));
    }