Beispiel #1
0
    public static JsonWrappers.ViewerLoadParams Step1_Submit(string TitleInput, string DescriptionInput, string TagsInput)
    {
        FileStatus currentStatus = (FileStatus)HttpContext.Current.Session["fileStatus"];
        var        fileName      = TitleInput.Trim().Replace(' ', '_').ToLower();

        if (currentStatus.hashname.LastIndexOf(".skp") != -1)
        {
            fileName += ".skp";
        }
        else
        {
            fileName += ".zip";
        }
        if (currentStatus != null)
        {
            currentStatus.filename = fileName;
        }

        ContentObject tempFedoraCO = (ContentObject)HttpContext.Current.Session["contentObject"];

        tempFedoraCO.PID = "";

        HttpServerUtility serverUtil = HttpContext.Current.Server;

        tempFedoraCO.Title       = serverUtil.HtmlEncode(TitleInput.Trim());
        tempFedoraCO.Description = serverUtil.HtmlEncode(DescriptionInput.Trim());

        if (currentStatus.type == FormatType.VIEWABLE)
        {
            tempFedoraCO.Location = fileName.Replace(".skp", ".zip");
        }

        string cleanTags = "";

        foreach (string s in TagsInput.Split(','))
        {
            cleanTags += s.Trim() + ",";
        }
        cleanTags             = serverUtil.HtmlEncode(cleanTags.Trim(','));
        tempFedoraCO.Keywords = cleanTags;

        JsonWrappers.ViewerLoadParams jsReturnParams = new JsonWrappers.ViewerLoadParams();


        if (currentStatus.type == FormatType.VIEWABLE)
        {
            tempFedoraCO.DisplayFile       = currentStatus.filename.Replace("zip", "o3d").Replace("skp", "o3d");
            jsReturnParams.IsViewable      = true;
            jsReturnParams.BasePath        = "../Public/Serve.ashx?mode=PreviewTempModel";
            jsReturnParams.TempArchiveName = currentStatus.hashname.Replace("skp", "zip");
            jsReturnParams.UpAxis          = tempFedoraCO.UpAxis;
            jsReturnParams.UnitScale       = tempFedoraCO.UnitScale;
            jsReturnParams.NumPolygons     = tempFedoraCO.NumPolygons;
        }
        HttpContext.Current.Session["contentObject"] = tempFedoraCO;
        return(jsReturnParams);
    }
Beispiel #2
0
    public static string HtmlEncode(string s)
    {
        HttpServerUtility server = System.Web.HttpContext.Current.Server;

        if (server != null && s != null)
        {
            return(server.HtmlEncode(s).Replace(server.HtmlEncode("<font color=red><b>"), "<font color=red><b>").Replace(server.HtmlEncode("</b></font>"), "</b></font>"));
        }
        else
        {
            return(string.Empty);
        }
    }
 public static IEnumerable <string> FormatAsHtml <K, V>(this IDictionary <K, V> dict, string format)
 {
     foreach (var pair in dict)
     {
         yield return(HttpServerUtility.HtmlEncode(string.Format(format, pair.Key, pair.Value)));
     }
 }
Beispiel #4
0
 public string Encode(string s)
 {
     if (String.IsNullOrEmpty(s))
     {
         throw new ArgumentNullException("s");
     }
     return(_server.HtmlEncode(s));
 }
Beispiel #5
0
        public bool SendErrorAlert(Exception ex, string extraInfo)
        {
            HttpServerUtility server = HttpContext.Current.Server;

            MailAddress           from = new MailAddress(Settings.Default.CustomerServiceEmail);
            MailAddressCollection tos  = new MailAddressCollection();

            tos.Add(new MailAddress(Settings.Default.CompanyContactEmail));
            string title   = "Exception Alert";
            string subject = "Exception Alert";

            StringBuilder sb = new StringBuilder();

            sb.Append("<div>" + server.HtmlEncode(ex.Message) + "</div>");
            if (!String.IsNullOrEmpty(extraInfo))
            {
                sb.Append("<div>Extra info:</div>");
                sb.Append("<div>" + SiteUtils.SurroundTextBlocksWithHtmlTags(extraInfo, "div", null) + "</div>");
            }
            sb.Append("<div>Exception data:</div><table>");
            foreach (DictionaryEntry entry in ex.Data)
            {
                sb.Append("<tr>");

                sb.Append("<td style=\"border-bottom: solid 1px #cccccc;\">");
                sb.Append(server.HtmlEncode(entry.Key.ToString()));
                sb.Append("</td>");

                sb.Append("<td style=\"border-bottom: solid 1px #cccccc;\">");
                sb.Append(server.HtmlEncode(entry.Value.ToString()));
                sb.Append("<td>");

                sb.Append("</tr>");
            }
            sb.Append("</table>");

            string message = sb.ToString();
            string body    = StandardHtmlFormattedMessage(title, message, false);

            return(SendMessage(from, null, tos, null, null, subject, body, true));
        }
        public void ProcessRequest(System.Web.HttpContext context)
        {
            // Make the HTTP context objects easily available.
            HttpResponse      response = context.Response;
            HttpRequest       request  = context.Request;
            HttpServerUtility server   = context.Server;

            response.Write("<html><body>");

            // Get the name of the requested file.
            string file = request.QueryString["file"];

            try
            {
                // Open the file and display its contents, one line at a time.
                response.Write("<b>Listing " + file + "</b><br>");
                StreamReader r    = File.OpenText(server.MapPath(Path.Combine("./", file)));
                string       line = "";
                while (line != null)
                {
                    line = r.ReadLine();

                    if (line != null)
                    {
                        // Make sure tags and other special characters are
                        // replaced by their corresponding HTML entities, so they
                        // can be displayed appropriately.
                        line = server.HtmlEncode(line);

                        // Replace spaces and tabs with non-breaking spaces
                        // to preserve whitespace.
                        line = line.Replace(" ", "&nbsp;");
                        line = line.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

                        // A more sophisticated source viewer might apply color-coding.
                        response.Write(line + "<br>");
                    }
                }
                r.Close();
            }
            catch (ApplicationException err)
            {
                response.Write(err.Message);
            }
            response.Write("</html></body>");
        }
        public string FormatHTML(string source, HttpServerUtility Server)  //处理a标签和其他html标签的显示
        {
            bool isMulti = false;

            if (string.IsNullOrEmpty(source))
            {
                return("");
            }
            if (source.IndexOf("<a") > -1 && source.IndexOf("href") > -1 && source.IndexOf("</a>") > source.IndexOf("<a"))
            {
                StringBuilder sb     = new StringBuilder();
                string        first  = source.IndexOf("<a") > 0 ? source.Substring(0, source.IndexOf("<a")) : "";
                string        second = source.Substring(source.IndexOf("<a"), source.IndexOf("</a>") - source.IndexOf("<a") + 4);
                string        third  = source.Substring(source.IndexOf("</a>") + 4);
                if (!string.IsNullOrEmpty(first))
                {
                    sb.Append(Server.HtmlEncode(first));
                }
                sb.Append(second);
                while (third.IndexOf("<a") > -1 && third.IndexOf("href") > -1 && third.IndexOf("</a>") > third.IndexOf("<a"))
                {
                    first  = third.IndexOf("<a") > 0 ? third.Substring(0, third.IndexOf("<a")) : "";
                    second = third.Substring(third.IndexOf("<a"), third.IndexOf("</a>") - third.IndexOf("<a") + 4);
                    third  = third.Substring(third.IndexOf("</a>") + 4);
                    if (!string.IsNullOrEmpty(first))
                    {
                        sb.Append(Server.HtmlEncode(first));
                    }
                    sb.Append(second);
                    if (!string.IsNullOrEmpty(third))
                    {
                        sb.Append(Server.HtmlEncode(third));
                    }
                    isMulti = true;
                }
                if (!string.IsNullOrEmpty(third) && !isMulti)
                {
                    sb.Append(Server.HtmlEncode(third));
                }
                return(sb.ToString());
            }
            else
            {
                string a = Server.HtmlEncode(source);
                return(Server.HtmlEncode(source));
            }
        }
Beispiel #8
0
 public DataView GetDataView(HttpServerUtility encoder)
 {
     if (ds != null && ds.Tables.Count > 0)
     {
         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
         {
             for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
             {
                 try
                 {
                     ds.Tables[0].Rows[i][j] = encoder.HtmlEncode(ds.Tables[0].Rows[i][j].ToString());
                 }
                 catch {}
             }
         }
         return(new DataView(ds.Tables[0]));
     }
     else
     {
         return(null);
     }
 }
 public override string HtmlEncode(string s)
 {
     return(_httpServerUtility.HtmlEncode(s));
 }
Beispiel #10
0
 public string HtmlEncode(string s)
 {
     return(_server.HtmlEncode(s));
 }
Beispiel #11
0
 /// <summary>
 /// HTML encodes a string and returns the encoded string.
 /// </summary>
 /// <param name="content">The text string to HTML encode.</param>
 /// <returns>The HTML encoded text.</returns>
 public String HtmlEncode(String content)
 {
     return(server.HtmlEncode(content));
 }
        //20170116 adding commentws for email notification
        //public static void SendNotifications<T>( HttpServerUtility server, GCCPropertyShortCode property, SurveyType surveyType, NotificationReason reason, T replacementModel, string emailAddress, string subjectPrefix )
        public static void SendNotifications <T>(HttpServerUtility server, GCCPropertyShortCode property, SurveyType surveyType, NotificationReason reason, string Comments, T replacementModel, string emailAddress, string subjectPrefix, int operationsArea)
            where T : class
        {
            string template     = String.Empty;
            string title        = String.Empty;
            string propertyName = PropertyTools.GetCasinoName((int)property);

            if (property == GCCPropertyShortCode.GAG)
            {
                PropertyInfo nameProp = replacementModel.GetType().GetProperty("CasinoName");
                if (nameProp != null)
                {
                    string name = nameProp.GetValue(replacementModel) as string;
                    if (!String.IsNullOrWhiteSpace(name))
                    {
                        propertyName = name;
                    }
                }
            }
            switch (surveyType)
            {
            case SurveyType.GEI:
                if (reason == NotificationReason.ThankYou)
                {
                    title    = "Thank You For Your Feedback";
                    template = "GEIThankYou";
                }
                else
                {
                    template = "GEITemplate";
                    title    = String.Format("{0}GEI Feedback Notification for {1} - {2}", subjectPrefix, propertyName, DateTime.Now.ToString("MMMM dd, yyyy"));
                }
                break;

            case SurveyType.GEIProblemResolution:
                if (reason == NotificationReason.ThankYou)
                {
                    title    = "Thank You For Your Feedback";
                    template = "GEIThankYou";
                }
                else
                {
                    if (replacementModel.ToString().Contains("FeedbackCategory"))
                    {
                        template = "GEIFeedbackCategoryTemplate";
                        title    = String.Format("{0}GEI Feedback Category Notification for {1} - {2}", subjectPrefix, propertyName, DateTime.Now.ToString("MMMM dd, yyyy"));
                    }
                    else
                    {
                        template = "GEITemplate";
                        title    = String.Format("{0}GEI Problem Resolution Feedback Notification for {1} - {2}", subjectPrefix, propertyName, DateTime.Now.ToString("MMMM dd, yyyy"));
                    }
                }
                break;

            case SurveyType.Hotel:
                if (reason == NotificationReason.ThankYou)
                {
                    title    = "Thank You For Your Feedback";
                    template = "HotelThankYou";
                }
                else
                {
                    template = "HotelTemplate";
                    title    = String.Format("{0}Hotel Survey Notification - {1}", subjectPrefix, DateTime.Now.ToString("MMMM dd, yyyy"));
                }
                break;

            case SurveyType.Feedback:
                if (reason == NotificationReason.ThankYou)
                {
                    title    = "Thank You For Your Feedback";
                    template = "FeedbackThankYou";
                }
                else if (reason == NotificationReason.Tier3Alert)
                {
                    title    = String.Format("{0}Tier 3 Alert for {1} - {2}", subjectPrefix, propertyName, DateTime.Now.ToString("MMMM dd, yyyy"));
                    template = "Tier3Alert";
                }
                else
                {
                    template = "FeedbackTemplate";
                    title    = String.Format("{0}Feedback Follow-up Notification for {1} - {2}", subjectPrefix, propertyName, DateTime.Now.ToString("MMMM dd, yyyy"));
                }
                break;

            case SurveyType.Donation:
                template = "DonationTemplate";
                title    = String.Format("{0}Sponsorship / Donation Request Notification for {1} - {2}", subjectPrefix, propertyName, DateTime.Now.ToString("MMMM dd, yyyy"));
                break;
            }
            if (template.Equals(String.Empty))
            {
                return;
            }
            MailMessage msg = null;

            try {
                string path = server.MapPath("~/Content/notifications/");
                msg = EmailManager.CreateEmailFromTemplate(
                    Path.Combine(path, template + ".htm"),
                    Path.Combine(path, template + ".txt"),
                    replacementModel);
                PropertyInfo attachmentProp = replacementModel.GetType().GetProperty("Attachments");
                if (attachmentProp != null)
                {
                    SurveyAttachmentDetails[] attachments = attachmentProp.GetValue(replacementModel) as SurveyAttachmentDetails[];
                    foreach (SurveyAttachmentDetails att in attachments)
                    {
                        LinkedResource lr = new LinkedResource(server.MapPath(att.Path));
                        lr.ContentId = att.ContentID;
                        msg.AlternateViews[0].LinkedResources.Add(lr);
                    }
                }
                msg.From    = new MailAddress("*****@*****.**");
                msg.Subject = title;
                //Add high priority flag to tier 3 alerts
                if (reason == NotificationReason.Tier3Alert)
                {
                    msg.Priority = MailPriority.High;
                }
                bool hasAddress = false;
                if (!String.IsNullOrEmpty(emailAddress))
                {
                    msg.To.Add(emailAddress);
                    hasAddress = true;
                }
                else
                {
                    SQLDatabase sql = new SQLDatabase();    sql.CommandTimeout = 120;
                    DataTable   dt  = sql.QueryDataTable(@"
SELECT [SendType], u.[FirstName], u.[LastName],  u.[Email]
FROM [tblNotificationUsers] ne
	INNER JOIN [tblNotificationPropertySurveyReason] psr
		ON ne.[PropertySurveyReasonID] = psr.[PropertySurveyReasonID]
	INNER JOIN [tblCOM_Users] u
		ON ne.UserID = u.UserID
WHERE psr.PropertyID = @PropertyID
	AND psr.SurveyTypeID = @SurveyID
	AND psr.ReasonID = @ReasonID
	
;",
                                                         //AND ( ( @OperationsAreaID < 0 AND psr.OperationsAreaID IS NULL ) OR psr.OperationsAreaID = @OperationsAreaID )
                                                         new SQLParamList()
                                                         .Add("@PropertyID", (int)property)
                                                         .Add("@SurveyID", (int)surveyType)
                                                         .Add("@ReasonID", (int)reason)
                                                         .Add("@OperationsAreaID", operationsArea)
                                                         );
                    if (!sql.HasError && dt.Rows.Count > 0)
                    {
                        StringBuilder addrs = new StringBuilder();
                        foreach (DataRow dr in dt.Rows)
                        {
                            switch (dr["SendType"].ToString())
                            {
                            case "1":
                                msg.To.Add(dr["Email"].ToString());
                                //201701 Testing Email error
                                //msg.Bcc.Add("*****@*****.**");
                                addrs.Append(dr["FirstName"].ToString() + " " + dr["LastName"].ToString() + " <" + dr["Email"].ToString() + ">" + "\n");
                                hasAddress = true;
                                break;

                            case "2":
                                msg.CC.Add(dr["Email"].ToString());
                                //201701 Testing Email error
                                //msg.Bcc.Add("*****@*****.**");
                                //Colin requested that CC addresses not show on the call Aug 10,2015
                                //addrs.Append( dr["FirstName"].ToString() + " " + dr["LastName"].ToString() + " <" + dr["Email"].ToString() + ">" + "\n" );
                                hasAddress = true;
                                break;

                            case "3":
                                msg.Bcc.Add(dr["Email"].ToString());
                                //201701 Testing Email error
                                // msg.Bcc.Add("*****@*****.**");
                                hasAddress = true;
                                break;
                            }
                        }
                        using (StreamReader sr = new StreamReader(msg.AlternateViews[0].ContentStream)) {
                            msg.AlternateViews[0] = AlternateView.CreateAlternateViewFromString(sr.ReadToEnd().Replace("{Recipients}", server.HtmlEncode(addrs.ToString()).Replace("\n", "<br />")).Replace("{Business}", server.HtmlEncode(reason.ToString()).Replace("\n", "<br />")).Replace("{Comments}", server.HtmlEncode(Comments.ToString()).Replace("\n", "<br />")), null, MediaTypeNames.Text.Html);
                        }
                        using (StreamReader sr = new StreamReader(msg.AlternateViews[1].ContentStream)) {
                            msg.AlternateViews[1] = AlternateView.CreateAlternateViewFromString(sr.ReadToEnd().Replace("{Recipients}", addrs.ToString()).Replace("{Business}", reason.ToString()).Replace("{Comments}", Comments.ToString()), null, MediaTypeNames.Text.Plain);
                        }
                    }
                }

                if (hasAddress)
                {
                    msg.Send();
                }
            } catch (Exception ex) {
            } finally {
                if (msg != null)
                {
                    msg.Dispose();
                    msg = null;
                }
            }
        }
Beispiel #13
0
 public static string FromXmlName2Render(this string s, HttpServerUtility sr)
 {
     return(sr.HtmlEncode(XmlConvert.DecodeName(s)));
 }
Beispiel #14
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);
        }
    }
Beispiel #15
0
		public static string GetValue(DataRow row, string field) {
			if (row[field].ToString() == null)
				return "";
			else
				return Server.HtmlEncode(row[field].ToString());
		}
Beispiel #16
0
    public static string SubmitUpload(string DeveloperName, string ArtistName, string DeveloperUrl,
                                      string SponsorName, string LicenseType,
                                      bool RequireResubmit)
    {
        HttpServerUtility server = HttpContext.Current.Server;
        ContentObject     tempCO = (ContentObject)HttpContext.Current.Session["contentObject"];

        try
        {
            FileStatus status = (FileStatus)HttpContext.Current.Session["fileStatus"];

            var             factory = new DataAccessFactory();
            IDataRepository dal     = factory.CreateDataRepositorProxy();
            dal.InsertContentObject(tempCO);
            tempCO.DeveloperName      = server.HtmlEncode(DeveloperName);
            tempCO.ArtistName         = server.HtmlEncode(ArtistName);
            tempCO.MoreInformationURL = server.HtmlEncode(DeveloperUrl);
            tempCO.RequireResubmit    = RequireResubmit;
            tempCO.SponsorName        = server.HtmlEncode(SponsorName);
            vwarDAL.PermissionsManager perMgr = new PermissionsManager();
            var groupSetReturnCode            = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AllUsers, ModelPermissionLevel.Fetchable);
            groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AnonymousUsers, ModelPermissionLevel.Searchable);

            string pid = tempCO.PID;
            //tempCO.SponsorURL = SponsorUrl; !missing SponsorUrl metadata in ContentObject

            if (LicenseType == "publicdomain")
            {
                tempCO.CreativeCommonsLicenseURL = "http://creativecommons.org/publicdomain/mark/1.0/";
            }
            else
            {
                tempCO.CreativeCommonsLicenseURL = String.Format(ConfigurationManager.AppSettings["CCBaseUrl"], LicenseType);
            }


            //Upload the thumbnail and logos
            string filename = status.hashname;
            string basehash = filename.Substring(0, filename.LastIndexOf(".") - 1);
            foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/App_Data/imageTemp")).GetFiles("*" + basehash + "*"))
            {
                using (FileStream fstream = f.OpenRead())
                {
                    string type = f.Name.Substring(0, f.Name.IndexOf('_'));
                    switch (type)
                    {
                    case ImagePrefix.DEVELOPER_LOGO:
                        tempCO.DeveloperLogoImageFileName   = "developer_logo" + f.Extension;
                        tempCO.DeveloperLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.DeveloperLogoImageFileName);
                        break;

                    case ImagePrefix.SPONSOR_LOGO:
                        tempCO.SponsorLogoImageFileName   = "sponsor_logo" + f.Extension;
                        tempCO.SponsorLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.SponsorLogoImageFileName);
                        break;

                    case ImagePrefix.SCREENSHOT:
                        tempCO.ScreenShot   = "screenshot" + f.Extension;
                        tempCO.ScreenShotId = dal.SetContentFile(fstream, tempCO.PID, tempCO.ScreenShot);

                        System.Drawing.Imaging.ImageFormat fmt = System.Drawing.Imaging.ImageFormat.Png;
                        if (f.Extension == ".png")
                        {
                            fmt = System.Drawing.Imaging.ImageFormat.Png;
                        }
                        else if (f.Extension == ".jpg")
                        {
                            fmt = System.Drawing.Imaging.ImageFormat.Jpeg;
                        }
                        else if (f.Extension == ".gif")
                        {
                            fmt = System.Drawing.Imaging.ImageFormat.Gif;
                        }
                        else
                        {
                            throw new Exception("Invalid screenshot format");
                        }

                        tempCO.ThumbnailId = Website.Common.GetFileSHA1AndSalt(fstream) + f.Extension;
                        using (FileStream outFile = new FileStream(HttpContext.Current.Server.MapPath("~/thumbnails/" + tempCO.ThumbnailId), FileMode.Create))
                            Website.Common.GenerateThumbnail(fstream, outFile, fmt);

                        break;

                    default:
                        break;
                    }
                }
            }
            string dataPath = HttpContext.Current.Server.MapPath("~/App_Data/");
            if (status.type == FormatType.VIEWABLE)
            {
                //Upload the original file
                using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open))
                {
                    tempCO.OriginalFileId   = dal.SetContentFile(s, pid, "original_" + status.filename);
                    tempCO.OriginalFileName = "original_" + status.filename;
                }
                using (FileStream s = new FileStream(Path.Combine(dataPath, "converterTemp/" + status.hashname.ToLower().Replace("skp", "zip")), FileMode.Open, FileAccess.Read))
                {
                    tempCO.DisplayFileId = dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "zip"));
                }
                using (FileStream s = new FileStream(Path.Combine(dataPath, "viewerTemp/" + status.hashname.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")), FileMode.Open))
                {
                    dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "o3d").Replace("zip", "o3d"));
                }
            }
            else if (status.type == FormatType.RECOGNIZED)
            {
                using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open))
                {
                    tempCO.OriginalFileName = "original_" + status.filename;
                    tempCO.OriginalFileId   = dal.SetContentFile(s, pid, tempCO.OriginalFileName);
                }
            }
            tempCO.Enabled      = true;
            tempCO.UploadedDate = DateTime.Now;

            dal.UpdateContentObject(tempCO);
            UploadReset(status.hashname);

            List <string> textureReferences = HttpContext.Current.Session["contentTextures"] as List <string>;

            List <string> textureReferenceMissing = HttpContext.Current.Session["contentMissingTextures"] as List <string>;



            if (textureReferences != null)
            {
                foreach (string tex in textureReferences)
                {
                    tempCO.SetParentRepo(dal);
                    tempCO.AddTextureReference(tex, "unknown", 0);
                }
            }
            if (textureReferenceMissing != null)
            {
                foreach (string tex in textureReferenceMissing)
                {
                    tempCO.SetParentRepo(dal);
                    tempCO.AddMissingTexture(tex, "unknown", 0);
                }
            }

            if (LR_3DR_Bridge.LR_Integration_Enabled())
            {
                LR_3DR_Bridge.ModelUploaded(tempCO);
            }

            Website.Mail.SendModelUploaded(tempCO);
            dal.Dispose();
            perMgr.Dispose();
            return(tempCO.PID);
        }
        catch (Exception e)
        {
            #if DEBUG
            return(String.Format("fedoraError|" + e.Message + "<br /><br />" + e.StackTrace));
            #else
            return("fedoraError|" + ConfigurationManager.AppSettings["UploadPage_FedoraError"]);
            #endif
        }
    }
 public static string RawUrl(this HtmlHelper html, string url)
 {
     return(html.Raw(HttpServerUtility.HtmlEncode(url)));
 }
        public void Methods_Deny_Unrestricted()
        {
            hsu.ClearError();

            Assert.IsNull(hsu.GetLastError(), "GetLastError");

            Assert.IsNotNull(hsu.HtmlDecode(String.Empty), "HtmlDecode(string)");
            hsu.HtmlDecode(String.Empty, sw);

            Assert.IsNotNull(hsu.HtmlEncode(String.Empty), "HtmlEncode(string)");
            hsu.HtmlEncode(String.Empty, sw);

            try
            {
                Assert.IsNull(hsu.MapPath(String.Empty), "MapPath(string)");
            }
            catch (NullReferenceException)
            {
                // ms 1.x
            }

            try
            {
                hsu.Transfer("/");
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.Transfer("/", true);
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.Transfer("/", false);
            }
            catch (NullReferenceException)
            {
                // ms
            }
#if NET_2_0
            try
            {
                hsu.Transfer((IHttpHandler)null, true);
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.Transfer((IHttpHandler)null, false);
            }
            catch (NullReferenceException)
            {
                // ms
            }
#endif
            try
            {
                Assert.IsNotNull(hsu.UrlDecode(url), "UrlDecode(string)");
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.UrlDecode("http://www.mono-project.com/", sw);
            }
            catch (NullReferenceException)
            {
                // ms
            }

            Assert.IsNotNull(hsu.UrlEncode(String.Empty), "UrlEncode(string)");
            hsu.UrlEncode(String.Empty, sw);

            Assert.IsNotNull(hsu.UrlPathEncode(String.Empty), "UrlPathEncode(string)");
        }
Beispiel #19
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.RemoveHeader("Connection");

            if (!String.IsNullOrEmpty(_rootFolder) && context.Request.Path != null)
            {
                string filename = Path.Combine(_rootFolder, context.Request.Path.Replace("/", "\\").Substring(1));
                if (filename.IndexOf("..") < 0 && filename.ToLower().StartsWith(_rootFolder.ToLower()))   // ensure that the files are below _rootFolder
                {
                    if (File.Exists(filename))
                    {
                        if (Path.GetExtension(filename) == ".htm")
                        {
                            context.Response.ContentType = "text/html; charset=UTF-8";
                        }
                        else if (Path.GetExtension(filename) == ".jpg")
                        {
                            context.Response.ContentType = "image/jpeg";
                        }
                        else if (Path.GetExtension(filename) == ".xml")
                        {
                            context.Response.ContentType = "text/xml; charset=UTF-8";
                        }

                        context.Response.Write(File.ReadAllBytes(filename));
                        return;
                    }
                }
            }

            switch (context.Request.Path)
            {
            case "/throwerror":
                throw new HttpException(MFToolkit.Net.Web.HttpStatusCode.InternalServerError);

            case "/filenotfound":
                throw new HttpException(MFToolkit.Net.Web.HttpStatusCode.NotFound);

            case "/imbot":
                context.Response.ContentType = "text/html; charset=UTF-8";

                switch (context.Request.Form["step"])
                {
                case "1":
                    context.Response.Write("Hi, what's your name?");
                    break;

                case "2":
                    context.Response.Write("Hi " + HttpServerUtility.HtmlEncode(context.Request["value1"]) + ", where do you live?");
                    break;

                case "3":
                    context.Response.WriteLine("Well, welcome to this hello world bot, " + HttpServerUtility.HtmlEncode(context.Request["value1"]) + " from " + HttpServerUtility.HtmlEncode(context.Request["value2"]) + ".");
                    context.Response.WriteLine("<br>");
                    context.Response.Write("Which temperature do you want to read?<br>A : Kitchen<br>B : Simulated<br>Hit A or B and press enter...");
                    break;

                case "4":
                    if (context.Request["value3"] == "A")
                    {
                        context.Response.WriteLine("In the kitchen it is " + Program.temperature + HttpServerUtility.HtmlEncode(" °C."));
                    }
                    else if (context.Request["value3"] == "B")
                    {
                        context.Response.WriteLine("In the simulated room it is " + new Random().Next(17, 20) + HttpServerUtility.HtmlEncode(" °C."));
                    }
                    else
                    {
                        context.Response.WriteLine("I don't know this room.");
                    }

                    context.Response.WriteLine("<br>");
                    context.Response.WriteLine("<br>");
                    context.Response.WriteLine("Visit my blog at http://netmicroframework.blogspot.com/");
                    context.Response.Write("<reset>");
                    break;


                default:
                    context.Response.Write("<goto=1>");
                    break;
                }

                break;

            case "/test":
                context.Response.Redirect("/test.aspx");
                break;

            case "/test2.aspx":
                context.Response.ContentType = "text/html; charset=UTF-8";
                context.Response.Write("<html><head><title></title></head><body>" + (context.Request.Body != null ? Encoding.UTF8.GetString(context.Request.Body) : "<i>no body found</i>") + "</body></html>");
                break;

            case "/cookie":
                context.Response.ContentType = "text/html; charset=UTF-8";
                context.Response.Write("<html><head><title></title></head><body>");

                if (context.Request.Cookies.Count > 0)
                {
                    foreach (HttpCookie c in context.Request.Cookies)
                    {
                        context.Response.WriteLine("Cookie " + c.Name + " = " + c.Value + "<br/>");
                    }
                }

                HttpCookie cookie = new HttpCookie("test", DateTime.Now.ToString());
                cookie.Expires = DateTime.Now.AddDays(2);
                context.Response.SetCookie(cookie);
                context.Response.WriteLine("</body></html>");

                break;

            case "/test.aspx":
                context.Response.ContentType = "text/html; charset=UTF-8";
                context.Response.Write("<html><head><title></title><script type=\"text/javascript\" src=\"/scripts/test.js\"></script></head><body><form action=\"/test2.aspx\" method=\"post\"><input type=\"text\" id=\"txtbox1\" name=\"txtbox1\"/><input type=\"submit\" value=\"Post\"/></form></body></html>");
                break;

            case "/scripts/test.js":
                context.Response.ContentType = "text/javascript";
                context.Response.Write(@"
var c = 0;
var d = new Date();
function test() {
    var x = window.ActiveXObject ? new ActiveXObject(""Microsoft.XMLHTTP"") : new XMLHttpRequest();
    x.onreadystatechange = function() {
        if(x.readyState == 4) {
            if(x.status != 200)
                alert(x.status + ' ' + x.responseText);

            document.getElementById('txtbox1').value = x.responseText;
            if(++c <= 50)
                setTimeout(test, 1);
        }
    }
    x.open(""POST"", ""/test.ajax?x="" + c, true);
    x.send("""" + c);
}
setTimeout(test, 1);
");
                break;

            case "/test.ajax":

                context.Response.AddHeader("Cache-Control", "no-cache");
                context.Response.AddHeader("Pragma", "no-cache");

                if (context.Request.Body != null && context.Request.Body.Length > 0)
                {
                    context.Response.Write("ajax = " + Encoding.UTF8.GetString(context.Request.Body));
                }
                else
                {
                    context.Response.Write("ajax = could not read request");
                }

                break;

            default:
                context.Response.ContentType = "text/html; charset=UTF-8";
                context.Response.Write("<html><head><title>Control My World - How to switch lights on and heating off?</title></head><body>");


                context.Response.Write("<h1>Welcome to my .NET Micro Framework web server</h1><p>This demo server is running on a Tahoe-II board using XBee modules to communicate with XBee sensors from Digi.</p><p>On my device the current date is " + DateTime.Now + "</b><p><b>RawUrl: " + context.Request.RawUrl + "</b><br/>" + context.Request.Headers["User-Agent"] + "</p>");

                context.Response.Write("<p>Current temperature: " + Program.temperature + "°C</p>");

                if (context.Request.Params != null && context.Request.Params.Count > 0)
                {
                    context.Response.Write("<h3>Params</h3>");
                    context.Response.Write("<p style=\"color:blue\">");

                    foreach (string key in context.Request.Params.AllKeys)
                    {
                        context.Response.Write(key + " = " + context.Request.Params[key] + "<br/>");
                    }

                    context.Response.Write("</p>");
                }

                if (context.Request.Form != null && context.Request.Form.Count > 0)
                {
                    context.Response.Write("<h3>Form</h3>");
                    context.Response.Write("<p style=\"color:brown\">");

                    foreach (string key in context.Request.Form.AllKeys)
                    {
                        context.Response.Write(key + " = " + context.Request.Form[key] + "<br/>");
                    }

                    context.Response.Write("</p>");
                }

                if (context.Request.MimeContent != null)
                {
                    context.Response.Write("<h3>MIME Content</h3>");

                    foreach (string key in context.Request.MimeContent.AllKeys)
                    {
                        MimeContent mime = context.Request.MimeContent[key];

                        context.Response.Write("<p style=\"color:blue\">");
                        context.Response.Write(key + " =&gt; " + (mime.Content != null ? mime.Content.Length.ToString() : "0") + " bytes<br/>");

                        foreach (string mkey in context.Request.MimeContent[key].Headers.Keys)
                        {
                            context.Response.Write("<i>" + mkey + " : " + context.Request.MimeContent[key].Headers[mkey] + "</i><br/>");
                        }

                        context.Response.Write("</p>");



                        if (mime.Headers["Content-Type"] == "text/plain" && mime.Content != null && mime.Content.Length > 0)
                        {
                            context.Response.Write("<pre>" + Encoding.UTF8.GetString(mime.Content) + "</pre>");
                        }
                    }
                }

                if (context.Request.Headers != null && context.Request.Headers.Count > 0)
                {
                    context.Response.Write("<h3>HTTP Header</h3>");
                    context.Response.Write("<p style=\"color:green\">");

                    foreach (string key in context.Request.Headers.AllKeys)
                    {
                        context.Response.Write(key + " = " + context.Request.Headers[key] + "<br/>");
                    }

                    context.Response.Write("</p>");
                }

                if (context.Request.Body != null)
                {
                    context.Response.Write("<h3>Received Bytes:</h3>");
                    context.Response.Write("<p>" + context.Request.Body.Length + " bytes</p>");
                    context.Response.Write("<hr size=1/>");
                }

                context.Response.Write(@"<p><a href=""index.htm"">Demo HTML and JPEG (files on SD card)</a><br/>
<a href=""test.txt"">Demo Plain Text (file on SD card)</a><br/>
<a href=""test"">Redirect Test</a> calls /test and gets redirected to /test.aspx<br/>
<a href=""test.aspx"">AJAX Test</a> requests 5 times a value from webserver<br/>
<a href=""cookie"">Cookie Test</a> sets and displays a cookie<br/></p>
<a href=""#"" onclick=""this.href='HTMLPage1.htm';"">JavaScript demo test<br/></p>
<hr size=1/>
<p>Any feedback welcome: <a href=""http://weblogs.asp.net/mschwarz/contact.aspx"">contact</a>
<a href=""http://michael-schwarz.blogspot.com/"">My Blog</a> <a href=""http://weblogs.asp.net/mschwarz/"">My Blog (en)</a><br/>
<a href=""http://www.control-my-world.com/"">Control My World</a></p>
</body></html>");
                break;
            }
        }
Beispiel #20
0
 /// <summary>
 /// Formats a plain-text string with HTML formatting tags.
 /// </summary>
 /// <param name="server">The <see cref="HttpServerUtility"/> for processing web requests.</param>
 /// <param name="plainText">The plain-text string to format.</param>
 /// <returns>The HTML-formatted text.</returns>
 public static string HtmlFormat(this HttpServerUtility server, string plainText)
 {
     return(server.HtmlEncode(plainText).Replace("\n", "<br />"));
 }
        public void ProcessRequest(HttpContext context)
        {
            // Set defaults values
            string            data          = null;
            string            currentUserIp = "62.107.21.129";
            HttpRequest       currentR      = context.Request;
            HttpServerUtility currentS      = context.Server;
            int    currentLangId;
            bool   isValid            = true;
            bool   isUpdateInfoSucces = true;
            string errorMessage       = "succes";

            _currentUserIp = currentUserIp;

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

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

            string userAction = context.Request.QueryString["a"];

            if (string.IsNullOrEmpty(userAction))
            {
                isValid      = false;
                errorMessage = "You forgot action (querystring a)";
            }

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



            #region Go search

            SearchEngine engine = new SearchEngine();

            // default option
            SearchEngine.UserSearchOption userOption = SearchEngine.UserSearchOption.UpdateUserSearch;


            #region Set default user data

            var otherData = new
            {
                UserID        = (Guid)ANOProfile.GetCookieValues(currentUserIp, context).UserID,
                UserIpAddress = (string)currentUserIp
            };

            #endregion

            // Create user default information
            UserSearchInfo usi = new UserSearchInfo
            {
                UserID        = otherData.UserID,
                UserIpAddress = otherData.UserIpAddress
            };

            // CREATE match search!
            if (userAction == "1")
            {
                #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,
                    searchYearTo      = (int)MaxIntValue,
                    searchYearFrom    = (int)MaxIntValue,
                    searchDayTo       = (int)MaxIntValue,
                    searchDayFrom     = (int)MaxIntValue,
                    searchMonthTo     = (int)MaxIntValue,
                    searchMonthFrom   = (int)MaxIntValue,
                    searchHourFrom    = (int)MaxIntValue,
                    searchHourTo      = (int)MaxIntValue,
                    searchMinutesFrom = (int)MaxIntValue,
                    searchMinutesTo   = (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))

                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 = SearchEngine.UserSearchOption.CreateUserSearch;
            }


            // Update user activity
            if (userAction == "2")
            {
                userOption = SearchEngine.UserSearchOption.UpdateUserSearch;

                // Get UserSearchInfo from database
                usi.SearchMatchID  = ANOProfile.GetCookieValues(usi.UserIpAddress, context).SearchMatchID;
                isUpdateInfoSucces = engine.GetUserMatchInfo(usi);
            }

            if (userAction == "3")
            {
                userOption = SearchEngine.UserSearchOption.UpdateActivity;

                // Get UserSearchInfo from database
                usi.SearchMatchID  = ANOProfile.GetCookieValues(usi.UserIpAddress, context).SearchMatchID;
                isUpdateInfoSucces = engine.GetUserMatchInfo(usi);

                if (isValid == true)
                {
                    errorMessage = "UpdatingUserActivity";
                }
            }


            // Validate DateTimes
            if (isUpdateInfoSucces == true)
            {
                if (TimeNowValidate(usi.SearchMatchStart) == true)
                {
                    if (DateNowValidate(usi.SearchMatchStart) != true)
                    {
                        isValid      = false;
                        errorMessage = "FromDateIsSmallerThanDateNow";
                    }
                }
                else
                {
                    isValid      = false;
                    errorMessage = "FromTimeIsSmallerThanTimeNow";
                }
            }
            else
            {
                isValid      = false;
                errorMessage = "UserSearchMatchIsNotOnline";
            }

            SearchEngine.SearchNoticeMessage searchNotice     = SearchEngine.SearchNoticeMessage.Searching;
            const int           defaultMaxResult              = 10;
            const int           defaultPageIndex              = 0;
            const int           defaultMaxSearchTimeSeconds   = 1200;
            const int           defaultMinUserActivitySeconds = 10;
            const int           defaultFromLastSeconds        = 10;
            List <SearchObject> searchResult = engine.UserSearchMatch(usi,
                                                                      userOption,
                                                                      defaultMaxResult,
                                                                      defaultPageIndex,
                                                                      currentLangId,
                                                                      defaultMaxSearchTimeSeconds,
                                                                      defaultMinUserActivitySeconds,
                                                                      out searchNotice,
                                                                      defaultFromLastSeconds,
                                                                      context);


            #endregion
            LangaugeSystem ls      = new LangaugeSystem();
            string         getLang = ls.GetLang(Convert.ToInt32(sLangId)).LangShortname;
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(getLang);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(getLang);


            // Create documet and first element called "ss" for "Searchs"
            XDocument createXmlSearchs = new XDocument(
                new XDeclaration("1.0", "iso-8859-1", "true"),
                new XElement("ssi"));

            // Get element "ssi" for "Searchs"
            XElement getSearchsElement = createXmlSearchs.Descendants("ssi").Single();

            // items element
            getSearchsElement.Add(new XElement("is"));

            // Get element "is" for "Items"
            XElement getItemsElement = getSearchsElement.Descendants("is").Single();


            // check the result is  0
            if (searchResult != null)
            {
                if (searchResult.Count() > 0)
                {
                    TimeZoneManager mngInfo = new TimeZoneManager(currentUserIp);

                    // Insert/Create data as xml
                    for (int i = 0; i < searchResult.Count(); i++)
                    {
                        var s = searchResult[i];

                        // Create element data
                        getItemsElement.Add(
                            new XElement("i",
                                         new XAttribute("id", s.SearchWarID.ToString()),
                                         new XElement("cn", s.ClanName),
                                         new XElement("ct", new XAttribute("i", s.ClanContinentData.SearchWarContinentId),
                                                      s.ClanContinentData.SearchWarContinentName),
                                         new XElement("cy", new XAttribute("i", s.ClanCountryData.SearchWarCountrytId),
                                                      new XAttribute("t", s.ClanCountryData.SearchWarCountryTLD),
                                                      s.ClanCountryData.SearchWarCountryName),
                                         new XElement("cs",
                                                      new XAttribute("i",
                                                                     s.ClanSkillData != null
                                                                         ? s.ClanSkillData.SearchWarSkillId.ToString()
                                                                         : ""),
                                                      s.ClanSkillData != null ? s.ClanSkillData.SearchWarSkillName : ""),
                                         new XElement("st", new XAttribute("i", s.SearchContinentData.SearchWarContinentId),
                                                      s.SearchContinentData.SearchWarContinentName),
                                         new XElement("sy",
                                                      new XAttribute("i",
                                                                     s.SearchCountryData != null
                                                                         ? s.SearchCountryData.SearchWarCountrytId.ToString()
                                                                         : ""),
                                                      new XAttribute("t",
                                                                     s.SearchCountryData != null
                                                                         ? s.SearchCountryData.SearchWarCountryTLD
                                                                         : ""),
                                                      s.SearchCountryData != null
                                                          ? s.SearchCountryData.SearchWarCountryName
                                                          : ""),
                                         new XElement("ss",
                                                      new XAttribute("i",
                                                                     s.SearchSkillData != null
                                                                         ? s.SearchSkillData.SearchWarSkillId.ToString()
                                                                         : ""),
                                                      s.SearchSkillData != null ? s.SearchSkillData.SearchWarSkillName : ""),
                                         new XElement("g", new XAttribute("i", s.SearchGame.SearchWarGameId),
                                                      s.SearchGame.SearchWarGameName),
                                         new XElement("gt",
                                                      new XAttribute("i",
                                                                     s.SearchGameType != null
                                                                         ? s.SearchGameType.SearchWarGameTypeId.ToString()
                                                                         : ""),
                                                      s.SearchGameType != null ? s.SearchGameType.SearchWarGameTypeName : ""),
                                         new XElement("fd", mngInfo.ConvertDateTimeFromUtc(s.SearchMatchStart).ToString()),
                                         new XElement("x", s.SearchXvs),
                                         new XElement("y", s.SearchvsX),
                                         new XElement("m", s.SearchMap)));
                    }
                }
                else
                {
                    if (isValid == true)
                    {
                        isValid      = false;
                        errorMessage = "NoResults";


                        if (userAction == "3")
                        {
                            isValid      = true;
                            errorMessage = "UpdatingUserActivity";
                        }
                    }
                }
            }
            else
            {
                if (isValid == true)
                {
                    isValid      = false;
                    errorMessage = "NoResults";


                    if (userAction == "3")
                    {
                        isValid      = true;
                        errorMessage = "UpdatingUserActivity";
                    }
                }
            }

            // write status for result
            getSearchsElement.Add(new XElement("status", new XAttribute("bool", isValid.ToString()), errorMessage));

            // Write/save data
            StringWriter sw = new StringWriter();
            XmlWriter    w  = XmlWriter.Create(sw);
            createXmlSearchs.Save(w);

            w.Close();

            data = sw.ToString();
            sw.Close();

            context.Response.ContentType     = "text/xml";
            context.Response.ContentEncoding = Encoding.UTF8;
            context.Response.Write(XmlWhiteSpaceModule.RemoveWhitespace(data));

            // release it
            context.Response.Flush();

            engine.CleanUpAndClose();
        }
Beispiel #22
0
 public static string HtmlEncode(this string dataString)
 {
     return(HttpServerUtility.HtmlEncode(dataString));
 }
Beispiel #23
0
    public static JsonWrappers.UploadDetailDefaults Step2_Submit(string ScaleValue, string UpAxis)
    {
        HttpContext       context       = HttpContext.Current;
        HttpServerUtility server        = context.Server;
        FileStatus        currentStatus = (FileStatus)context.Session["fileStatus"];

        var             factory = new DataAccessFactory();
        IDataRepository dal     = factory.CreateDataRepositorProxy();
        ContentObject   tempCO  = (ContentObject)context.Session["contentObject"];

        tempCO.UpAxis    = server.HtmlEncode(UpAxis);
        tempCO.UnitScale = server.HtmlEncode(ScaleValue);
        //dal.UpdateContentObject(tempCO);
        context.Session["contentObject"] = tempCO;


        //Bind the
        JsonWrappers.UploadDetailDefaults jsReturnParams = new JsonWrappers.UploadDetailDefaults();
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            UserProfile p = null;
            try
            {
                p = UserProfileDB.GetUserProfileByUserName(context.User.Identity.Name);
            }
            catch { }

            if (p != null)
            {
                jsReturnParams.HasDefaults   = true;
                jsReturnParams.DeveloperName = p.DeveloperName;
                jsReturnParams.ArtistName    = p.ArtistName;
                jsReturnParams.DeveloperUrl  = p.WebsiteURL;
                jsReturnParams.SponsorName   = p.SponsorName;

                string tempImagePath = context.Server.MapPath("~/App_Data/imageTemp/");
                if (p.DeveloperLogo != null)
                {
                    string extension           = p.DeveloperLogoContentType.Substring(p.DeveloperLogoContentType.LastIndexOf("/") + 1);
                    string tempDevLogoFilename = "devlogo_" + currentStatus.hashname.Replace("zip", extension);
                    using (FileStream stream = new FileStream(tempImagePath + tempDevLogoFilename, FileMode.Create))
                    {
                        stream.Write(p.DeveloperLogo, 0, p.DeveloperLogo.Length);
                    }

                    jsReturnParams.DeveloperLogoFilename = tempDevLogoFilename;
                }

                if (p.SponsorLogo != null)
                {
                    string extension = p.SponsorLogoContentType.Substring(p.SponsorLogoContentType.LastIndexOf("/") + 1);
                    string tempSponsorLogoFilename = "sponsorlogo_" + currentStatus.hashname.Replace("zip", extension);
                    using (FileStream stream = new FileStream(tempImagePath + tempSponsorLogoFilename, FileMode.Create))
                    {
                        stream.Write(p.SponsorLogo, 0, p.SponsorLogo.Length);
                    }

                    jsReturnParams.SponsorLogoFilename = tempSponsorLogoFilename;
                }
            }
        }
        dal.Dispose();
        return(jsReturnParams);
    }
        public static void SendFeedbackNotifications(HttpServerUtility server, string feedbackUID, bool toGuest)
        {
            SQLDatabase  sql          = new SQLDatabase();    sql.CommandTimeout = 120;
            SQLParamList sqlParams    = new SQLParamList().Add("GUID", feedbackUID);
            DataSet      ds           = sql.ExecStoredProcedureDataSet("spFeedback_GetItem", sqlParams);
            string       GCCPortalUrl = ConfigurationManager.AppSettings["GCCPortalURL"].ToString();

            if (!sql.HasError && ds.Tables[0].Rows.Count > 0)
            {
                DataRow fbkDR = ds.Tables[0].Rows[0];
                GCCPropertyShortCode property   = (GCCPropertyShortCode)fbkDR["PropertyID"].ToString().StringToInt();
                SurveyType           surveyType = (SurveyType)fbkDR["SurveyTypeID"].ToString().StringToInt();
                NotificationReason   reason     = (NotificationReason)fbkDR["ReasonID"].ToString().StringToInt();

                string emailAddress = String.Empty;
                if (toGuest)
                {
                    if (ds.Tables[2].Columns.Contains("ContactEmail"))
                    {
                        emailAddress = ds.Tables[2].Rows[0]["ContactEmail"].ToString();
                    }
                    if (String.IsNullOrWhiteSpace(emailAddress) && ds.Tables[2].Columns.Contains("Email"))
                    {
                        emailAddress = ds.Tables[2].Rows[0]["Email"].ToString();
                    }
                    if (String.IsNullOrWhiteSpace(emailAddress) && ds.Tables[2].Columns.Contains("Q5Email"))
                    {
                        emailAddress = ds.Tables[2].Rows[0]["Q5Email"].ToString();
                    }
                    if (String.IsNullOrWhiteSpace(emailAddress))
                    {
                        //Nothing to do
                        return;
                    }
                }

                string template = String.Empty;
                string title    = String.Empty;
                object replacementModel;

                title = PropertyTools.GetCasinoName((int)property) + " - Feedback Reply Notification";
                if (toGuest)
                {
                    template         = "GuestFeedbackNotification";
                    replacementModel = new {
                        CasinoName  = PropertyTools.GetCasinoName((int)property),
                        Link        = GCCPortalUrl + "F/" + feedbackUID,
                        Attachments = new SurveyTools.SurveyAttachmentDetails[] {
                            new SurveyTools.SurveyAttachmentDetails()
                            {
                                Path = "~/Images/headers/" + PropertyTools.GetCasinoHeaderImage(property), ContentID = "HeaderImage"
                            }
                        }
                    };
                }
                else
                {
                    template         = "StaffFeedbackNotification";
                    replacementModel = new {
                        Date       = DateTime.Now.ToString("yyyy-MM-dd"),
                        CasinoName = PropertyTools.GetCasinoName((int)property),
                        Link       = GCCPortalUrl + "Admin/Feedback/" + feedbackUID
                    };
                }

                MailMessage msg = null;
                try {
                    string path = server.MapPath("~/Content/notifications/");
                    msg = EmailManager.CreateEmailFromTemplate(
                        Path.Combine(path, template + ".htm"),
                        Path.Combine(path, template + ".txt"),
                        replacementModel);
                    PropertyInfo attachmentProp = replacementModel.GetType().GetProperty("Attachments");
                    if (attachmentProp != null)
                    {
                        SurveyAttachmentDetails[] attachments = attachmentProp.GetValue(replacementModel) as SurveyAttachmentDetails[];
                        foreach (SurveyAttachmentDetails att in attachments)
                        {
                            LinkedResource lr = new LinkedResource(server.MapPath(att.Path));
                            lr.ContentId = att.ContentID;
                            msg.AlternateViews[0].LinkedResources.Add(lr);
                        }
                    }
                    msg.From    = new MailAddress("*****@*****.**");
                    msg.Subject = title;
                    bool hasAddress = false;
                    if (!String.IsNullOrWhiteSpace(emailAddress))
                    {
                        msg.To.Add(emailAddress);
                        hasAddress = true;
                    }
                    else
                    {
                        sql = new SQLDatabase();
                        DataTable dt = sql.QueryDataTable(@"
SELECT [SendType], u.[FirstName], u.[LastName],  u.[Email]
FROM [tblNotificationUsers] ne
	INNER JOIN [tblNotificationPropertySurveyReason] psr
		ON ne.[PropertySurveyReasonID] = psr.[PropertySurveyReasonID]
	INNER JOIN [tblCOM_Users] u
		ON ne.UserID = u.UserID
WHERE psr.PropertyID = @PropertyID
	AND psr.SurveyTypeID = @SurveyID
	AND psr.ReasonID = @ReasonID
;",
                                                          new SQLParamList()
                                                          .Add("@PropertyID", (int)property)
                                                          .Add("@SurveyID", (int)surveyType)
                                                          .Add("@ReasonID", (int)reason)
                                                          );
                        if (!sql.HasError && dt.Rows.Count > 0)
                        {
                            StringBuilder addrs = new StringBuilder();
                            foreach (DataRow dr in dt.Rows)
                            {
                                switch (dr["SendType"].ToString())
                                {
                                case "1":
                                    msg.To.Add(dr["Email"].ToString());
                                    addrs.Append(dr["FirstName"].ToString() + " " + dr["LastName"].ToString() + " <" + dr["Email"].ToString() + ">" + "\n");
                                    hasAddress = true;
                                    break;

                                case "2":
                                    msg.CC.Add(dr["Email"].ToString());
                                    //Colin requested that CC addresses not show on the call Aug 10,2015
                                    //addrs.Append( dr["FirstName"].ToString() + " " + dr["LastName"].ToString() + " <" + dr["Email"].ToString() + ">" + "\n" );
                                    hasAddress = true;
                                    break;

                                case "3":
                                    msg.Bcc.Add(dr["Email"].ToString());
                                    hasAddress = true;
                                    break;
                                }
                            }
                            using (StreamReader sr = new StreamReader(msg.AlternateViews[0].ContentStream))
                            {
                                msg.AlternateViews[0] = AlternateView.CreateAlternateViewFromString(sr.ReadToEnd().Replace("{Recipients}", server.HtmlEncode(addrs.ToString()).Replace("\n", "<br />")), null, MediaTypeNames.Text.Html);
                            }
                            using (StreamReader sr = new StreamReader(msg.AlternateViews[1].ContentStream))
                            {
                                msg.AlternateViews[1] = AlternateView.CreateAlternateViewFromString(sr.ReadToEnd().Replace("{Recipients}", addrs.ToString()), null, MediaTypeNames.Text.Plain);
                            }



                            //using (StreamReader sr = new StreamReader(msg.AlternateViews[0].ContentStream))
                            //{
                            //    msg.AlternateViews[0] = AlternateView.CreateAlternateViewFromString(sr.ReadToEnd().Replace("{Recipients}", server.HtmlEncode(addrs.ToString()).Replace("\n", "<br />")).Replace("{Business}", server.HtmlEncode(reason.ToString()).Replace("\n", "<br />")).Replace("{Comments}", server.HtmlEncode(Comments.ToString()).Replace("\n", "<br />")), null, MediaTypeNames.Text.Html);
                            //}
                            //using (StreamReader sr = new StreamReader(msg.AlternateViews[1].ContentStream))
                            //{
                            //    msg.AlternateViews[1] = AlternateView.CreateAlternateViewFromString(sr.ReadToEnd().Replace("{Recipients}", addrs.ToString()).Replace("{Business}", reason.ToString()).Replace("{Comments}", Comments.ToString()), null, MediaTypeNames.Text.Plain);
                            //}
                        }
                    }

                    if (hasAddress)
                    {
                        msg.Send();
                    }
                } catch (Exception ex) {
                } finally {
                    if (msg != null)
                    {
                        msg.Dispose();
                        msg = null;
                    }
                }
            }
        }
Beispiel #25
0
 public static string EscapeHtml(string unescaped)
 {
     return(HttpServerUtility.HtmlEncode(unescaped));
 }
Beispiel #26
0
 public static string FromXmlValue2Render(this string s, HttpServerUtility sr)
 {
     s = s.Replace("&apos;", "'");
     // incredible but this code is ok...
     return(sr.HtmlEncode(sr.HtmlDecode(s)));
 }
        public override PaymentHtmlForm GenerateHtmlForm(Order order, string teaCommerceContinueUrl, string teaCommerceCancelUrl, string teaCommerceCallBackUrl, string teaCommerceCommunicationUrl, IDictionary <string, string> settings)
        {
            order.MustNotBeNull("order");
            settings.MustNotBeNull("settings");
            settings.MustContainKey("payer_agentid", "settings");
            settings.MustContainKey("language", "settings");
            settings.MustContainKey("payment_methods", "settings");
            settings.MustContainKey("md5Key1", "settings");
            settings.MustContainKey("md5Key2", "settings");

            HttpServerUtility server = HttpContext.Current.Server;

            PaymentHtmlForm htmlForm = new PaymentHtmlForm
            {
                Action = "https://secure.pay-read.se/PostAPI_V1/InitPayFlow"
            };

            //Shop id
            htmlForm.InputFields["payer_agentid"] = server.HtmlEncode(settings["payer_agentid"]);

            //API version
            htmlForm.InputFields["payer_xml_writer"] = "payread_php_0_2_v08";

            XNamespace ns        = "http://www.w3.org/2001/XMLSchema-instance";
            XElement   payerData = new XElement("payread_post_api_0_2",
                                                new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
                                                new XAttribute(ns + "noNamespaceSchemaLocation", "payread_post_api_0_2.xsd")
                                                );

            //Seller details
            payerData.Add(new XElement("seller_details",
                                       new XElement("agent_id", server.HtmlEncode(settings["payer_agentid"]))
                                       ));

            //Buyer details
            payerData.Add(new XElement("buyer_details",
                                       new XElement("first_name", server.HtmlEncode(order.PaymentInformation.FirstName)),
                                       new XElement("last_name", server.HtmlEncode(order.PaymentInformation.LastName)),
                                       new XElement("address_line_1", server.HtmlEncode(string.Empty)),
                                       new XElement("address_line_2", server.HtmlEncode(string.Empty)),
                                       new XElement("postal_code", server.HtmlEncode(string.Empty)),
                                       new XElement("city", server.HtmlEncode(string.Empty)),
                                       new XElement("country_code", server.HtmlEncode(string.Empty)),
                                       new XElement("phone_home", server.HtmlEncode(string.Empty)),
                                       new XElement("phone_work", server.HtmlEncode(string.Empty)),
                                       new XElement("phone_mobile", server.HtmlEncode(string.Empty)),
                                       new XElement("email", server.HtmlEncode(order.PaymentInformation.Email)),
                                       new XElement("organisation", server.HtmlEncode(string.Empty)),
                                       new XElement("orgnr", server.HtmlEncode(string.Empty)),
                                       new XElement("customer_id", server.HtmlEncode(string.Empty))
                                       //new XElement( "your_reference", server.HtmlEncode( string.Empty ) )
                                       //new XElement( "options", server.HtmlEncode( string.Empty ) )
                                       ));

            //Purchase
            XElement purchaseList = new XElement("purchase_list");

            purchaseList.Add(new XElement("freeform_purchase",
                                          new XElement("line_number", 1),
                                          new XElement("description", server.HtmlEncode(settings.ContainsKey("totalName") ? settings["totalName"] : "Total")),
                                          new XElement("item_number", server.HtmlEncode(settings.ContainsKey("totalSku") ? settings["totalSku"] : "0001")),
                                          new XElement("price_including_vat", server.HtmlEncode(order.TotalPrice.Value.WithVat.ToString(CultureInfo.InvariantCulture))),
                                          new XElement("vat_percentage", server.HtmlEncode(0M.ToString(CultureInfo.InvariantCulture))),
                                          new XElement("quantity", server.HtmlEncode(1M.ToString(CultureInfo.InvariantCulture)))
                                          ));

            //Check that the Iso code exists
            Currency currency = CurrencyService.Instance.Get(order.StoreId, order.CurrencyId);

            if (!Iso4217CurrencyCodes.ContainsKey(currency.IsoCode))
            {
                throw new Exception("You must specify an ISO 4217 currency code for the " + currency.Name + " currency");
            }
            payerData.Add(new XElement("purchase",
                                       new XElement("currency", server.HtmlEncode(currency.IsoCode)),
                                       new XElement("reference_id", server.HtmlEncode(order.CartNumber)),
                                       purchaseList
                                       ));

            //Processing control
            payerData.Add(new XElement("processing_control",
                                       new XElement("success_redirect_url", server.HtmlEncode(teaCommerceContinueUrl)),
                                       new XElement("authorize_notification_url", server.HtmlEncode(teaCommerceCallBackUrl)),
                                       new XElement("settle_notification_url", server.HtmlEncode(teaCommerceCallBackUrl)),
                                       new XElement("redirect_back_to_shop_url", server.HtmlEncode(teaCommerceCancelUrl))
                                       ));

            //Database overrides
            payerData.Add(new XElement("database_overrides",
                                       new XElement("accepted_payment_methods",
                                                    settings["payment_methods"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(i =>
                                                                                                                                                   new XElement("payment_method", server.HtmlEncode(i))
                                                                                                                                                   )
                                                    ),
                                       new XElement("debug_mode", server.HtmlEncode(settings.ContainsKey("settings") && settings["test_mode"] == "true" ? "verbose" : "silent")),
                                       new XElement("test_mode", server.HtmlEncode(settings.ContainsKey("settings") ? settings["test_mode"] : "false")),
                                       new XElement("language", server.HtmlEncode(settings["language"]))
                                       ));

            //Add all data to the xml document
            XDocument xmlDocument = new XDocument(
                new XDeclaration("1.0", "ISO-8859-1", "yes"),
                payerData
                );

            htmlForm.InputFields["payer_data"]     = xmlDocument.ToString().ToBase64();
            htmlForm.InputFields["payer_checksum"] = GenerateMD5Hash(settings["md5Key1"] + htmlForm.InputFields["payer_data"] + settings["md5Key2"]);

            return(htmlForm);
        }