Create shortcodes in ASP.NET web applications - c#

I'm working on a website where there will be embedded a lot of YouTube videos. I want to make it a little easier to embed them into the articles of the page.
When writing this:
[youtube]SOMETHING[/youtube]
the page should automatically create this:
<iframe src="//www.youtube.com/embed/SOMETHING"
frameborder="0" allowfullscreen></iframe>
So - how do I do that? I've been searching around but haven't been able to find a right solution. Please throw your examples in ASP.NET / C#.

Creating shortcodes in ASP.NET is easy as a custom solution. Before you output your article do
String html = "[YOUTUBE]Something[\\YOUTUBE]";
String replacementHtml = "<iframe src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>";
Regex shortcodeRegex = new Regex(#"\[YOUTUBE\]([^\[\\]+)\[\\YOUTUBE\]");
String result = shortcodeRegex.Replace(html, replacementHtml);
Take note of the $1 in the replacementHtml. This is what is replaced by what is internal to the match.
Then output the result to the page.

Wordpress style short code application. It replaces the value [short code /] in the content coming from the database or in the variable in the variable with the user control content.
App_Code--> modul_islemler.cs
public class modul_islemler
{
public static string modul_olustur(string data){
string aranan = #"\[(.*?)\/\]";
Regex objRegex = new Regex(aranan);
MatchCollection objCol = objRegex.Matches(data);
foreach (Match item in objCol)
{data = data.Replace(item.Groups[0].Value, modul_yaz(item.Groups[1].Value.ToString()));
}
return data;
}
public static string modul_yaz(string sayfa)
{
string[] ayir = sayfa.Split(' ');
ArrayList myAL = new ArrayList();
foreach (string a in ayir)
{
myAL.Add(a);
}
if (myAL.Count < 2) myAL.Add("");
return LoadControl("~/plugins/" + myAL[0] + "/" + myAL[0] + ".ascx");
}
public static string LoadControl(string UserControlPath)
{
FormlessPage page = new FormlessPage();
page.EnableViewState = false;
// Create instance of the user control
UserControl userControl = (UserControl)page.LoadControl(UserControlPath);
page.Controls.Add(userControl);
//Write the control Html to text writer
StringWriter textWriter = new StringWriter();
//execute page on server
HttpContext.Current.Server.Execute(page, textWriter, false);
// Clean up code and return html
return textWriter.ToString();
}
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
page.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="detail">
<div class="container">
<asp:Literal ID="icerikLtrl" runat="server"></asp:Literal>
</div>
</div>
</asp:Content>
page.aspx.cs --> [slide_plugins /] shortcodes
public partial class page : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
string txt="<div>blala [slide_plugins /] blabla</div>";
icerikLtrl.Text = modul_islemler.modul_olustur(txt);
}
plugins/slide_plugins/slide_plugins.ascx
<asp:TextBox runat="server" ID="Txt1"></asp:TextBox>
<asp:Button runat="server" ID="btn1" OnClick="btn1_Click" Text="Submit"></asp:Button>
plugins/slide_plugins/slide_plugins.ascx.cs
protected override void OnLoad(EventArgs e)
{
//kontrol yüklendiğinde çalışacak kodlar
base.OnLoad(e);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeComponent();
}
private void InitializeComponent()
{
btn1.Click += new EventHandler(btn1_Click);
}
protected void btn1_Click(object sender, EventArgs e)// not working....
{
Txt1.Text = "Example"; // not working....
}

This is what i use to handle youtube shortcodes
<Extension> Public Function ConvertYouTubeShortCode(text As String) As String
Dim regex__1 As String = "\[youtube:.*?\]"
Dim matches As MatchCollection = Regex.Matches(text, regex__1)
If matches.Count = 0 Then
Return text
End If
Dim width As Int32 = 620
Dim height As Int32 = 349
Dim BaseURL As String = "http://www.youtube.com/v/"
For i As Integer = 0 To matches.Count - 1
Dim length As Int32 = "[youtube:".Length
Dim mediaFile As String = matches(i).Value.Substring(length, matches(i).Value.Length - length - 1)
Dim player As String = "<div class=""video-container""><iframe width=""{2}"" height=""{3}"" src=""{4}{1}"" frameborder=""0"" allowfullscreen></iframe></div>"
Return text.Replace(matches(i).Value, [String].Format(player, i, mediaFile, width, height, BaseURL))
Next
End Function

Related

Dynamically created LinkButton OnClick Event not firing on PostBack

I am quite new to ASP and I have been stuck on an issue for about a week. The issue is probably something to do with the Asp Page Life Cycle but I am unable to find how this can be resolved. The issue is that skipto(..) is never called when I click the LinkButton (that were created on first Page Load), which means the LinkButtons are not rendered.
Sample Code below:
// Code Behind
protected void Page_Load(object sender, EventArgs e)
{
loadData();
if (!Page.IsPostBack)
{
skiptof();
}
}
public void loadData() {
// Loads from database
}
public void skipto(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
if (btn != null)
{
if (btn.CommandArgument != null && btn.CommandArgument != "0")
{
int currPage = 1;
int.TryParse(btn.CommandArgument, out currPage);
skiptof(currPage);
}
}
}
public void skiptof(int currPage = 1)
{
int lastPage = // calculate from LoadData()
string pageDisabled = "";
// pages
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage)
{
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "")
{
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
pagesPageLink.Click += new EventHandler(skipto);
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
// page
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel runat="server" id="UpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<div id="details" runat="server"></div>
<div class="pagination text-center" id="pagination" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
Your problem is:
You didn't bind the data again on postback, I've modified your code a little bit, there are several problems:
in the method skipof:
public void skiptof(int currPage = 1) {
//Clear the controls here then add them again
pagination.Controls.Clear();
int lastPage = // calculate from LoadData()
string pageDisabled = "";
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage) {
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "") {
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
// you can directly assign the method to be called here, there is no need to create a new EventHandler
pagesPageLink.Click += PagesPageLink_Click;
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
You didn't bind the data again in postback, so I modified it:
Page Load:
protected void Page_Load(object sender, EventArgs e) {
//Remove the Page.IsPostBack checking
skiptof();
}
Please take note that the controls you added dynamically will be cleared and you have to add it again on postback to avoid data lost.
Then you'll be able to get the value on PagesPageLink_Click event:
The whole sample is here:
http://pastie.org/10503291

How to execute a class once and use the data in ASP.net page

I have the following class (UCNewWorkFlow) which calls a cache database and retrieves rows and adds it to a string array:
public partial class UCNewWorkflow : System.Web.UI.Page
{
private string Connectioncacha = "";
public UCNewWorkflow()
{
int temp;
if (IsItWorkDay(DateTime.Now))
{
temp = 21;
}
else
{
temp = 17;
}
try
{
CacheConnection CacheConnect = new CacheConnection();
CacheConnect.ConnectionString = Connectioncacha;
CacheConnect.Open();
String SQLtext = #"";
DataTable table = new DataTable();
CacheCommand Command = new CacheCommand(SQLtext, CacheConnect);
CacheDataReader Reader = Command.ExecuteReader();
string[] inArr = new string[4];
int k = 0;
if (Reader.HasRows)
{
while (Reader.Read())
{
inArr[k] = Reader["NotYetSeen"].ToString();
returnTime(Convert.ToInt32(inArr[k]));
k++;
}
}
}
catch (Exception ce)
{
}
}
public string returnTime(int inHowMany)
{
string strTime = "";
double future = 0;
DateTime dt = DateTime.Now;
if (inHowMany / 2.0 <= 1)
{
strTime = "15 mins";
}
else if (inHowMany == 0)
{
strTime = "<15 mins";
}
else if (inHowMany / 2.0 > 1)
{
future = Math.Ceiling((inHowMany / 2.0)) * 15;
DateTime tempdate = dt.AddMinutes(future);
TimeSpan result = tempdate - DateTime.Now;
strTime = ToReadableString(result);
}
return strTime;
}
}
The result of the SQL query:
I have the following labels in my ASP.net page:
<asp:Label ID="lblFirstRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblSecondRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblThirdRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblFourthRow" runat="server" Text="Label"></asp:Label>
The code-behind for the ASP.net page:
protected void Page_Load(object sender, EventArgs e)
{
UCNewWorkflow uc = new UCNewWorkflow();
}
At the moment, I can't access the label from the class file.
How can I modify the code so, I have to call the class once and it will populate all four labels.
You are trying to perform this database query during the page's constructor, so it is too early in the ASP.NET Web Forms page lifecycle to have access to those arrays. Those labels do not exist when your constructor is called; they are created during the page initialization event.
As NicoTek suggested, using the Page_Load event handler is a good way of updating these labels. However, if you do it his way, I do not see a reason why your class is inheriting from System.Web.UI.Page, I would recommend refactoring your code so that this and any other database operations exist in another class. This will allow you to reuse code and prevent clutter and repetition in your code-behind files.
It looks to me that you want to return the string array inArr as a property of your UCNewWorkflow class and then bind this to a repeater on the Page_Load of your code-behind as suggested by #NicoTek.
Your Repeater definition on the code-in-front should contain just one Label definition and then as data is bound to the Repeater a new instance of the label is created for each element in your string array.
More details on repeaters can be found at
http://www.w3schools.com/aspnet/aspnet_repeater.asp
you could do
protected void Page_Load(object sender, EventArgs e)
{
UCNewWorkflow uc = new UCNewWorkflow();
lblFirstRow.Text = "someString"
}

How to display xml string in a Label?

I am trying to get my HTML method below, to encode the string and display it on label, but I keep getting a blank page, on the client-side.
I have checked the viewsource and it shows no HTML output their also.
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e, string data)
{
if (!IsPostBack)
{
string a = createXMLPub(data);
// Label1.Text = HttpUtility.HtmlEncode(a);
Label1.Text = Server.HtmlEncode(a);
}
}
public static string createXMLPub(string data )
{
XElement xeRoot = new XElement("pub");
XElement xeName = new XElement("name", "###");
xeRoot.Add(xeName);
XElement xeCategory = new XElement("category", "#####");
xeRoot.Add(xeCategory);
XDocument xDoc = new XDocument(xeRoot);
data = xDoc.ToString();
return data;
}
HTML
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Content>
Please advice, to where I may be going wrong with this code. Many thanks
Your Page_Load isn't fired - re: the extra string data param doesn't match the signature for the event delegate
So:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string a = createXMLPub();
Label1.Text = Server.HtmlEncode(a);
}
}
public static string createXMLPub()
{
XElement xeRoot = new XElement("pub");
XElement xeName = new XElement("name", "###");
xeRoot.Add(xeName);
XElement xeCategory = new XElement("category", "#####");
xeRoot.Add(xeCategory);
XDocument xDoc = new XDocument(xeRoot);
return xDoc.ToString();
}
Hth...

passing values (through listbox) between webpages in asp.net-c#

~/Admin/AdimHome.aspx.cs C# code
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function Open() {");
sb.Append(string.Format("window.open('Chat.aspx?rid={0}'", lstRooms.SelectedValue));
sb.Append(", 'newwindow','toolbar=no,location=no,menubar=no,width=290,height=330,resizable=no,scrollbars=no,top=350,left=980,right=500');return false;");
sb.Append("}</script>");
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
lblFacultyNo.Text = Session["User_Id"].ToString();
lblUserType.Text = Session["User_Type"].ToString();
pnlChat.Visible = false;
}
~/Admin/Chat.aspx.cs page C# code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User_Id"] == null)
Response.Redirect("~/Admin/AdimHome.aspx");
if (string.IsNullOrEmpty(Request.QueryString["rid"]))
Response.Redirect("~/Admin/AdminHome.aspx");
txtMsg.Attributes.Add("onkeypress", "return clickButton(event,'btn')");
if (!IsPostBack)
{
hdnRoomID.Value = Request.QueryString["rid"];
ChatRoom room = ChatEngine.GetRoom(hdnRoomID.Value);
string prevMsgs = room.JoinRoom(Session["User_Id"].ToString(), Session["User_Id"].ToString());
txt.Text = prevMsgs;
foreach (string s in room.GetRoomUsersNames())
{
lstMembers.Items.Add(new ListItem(s, s));
}
}
}
want to pass lstRooms.SelectedValue to Chat.aspx.cs page to check as per client request to differentiate their chat rooms:
sb.Append(string.Format("window.open('Chat.aspx?rid={0}'", lstRooms.SelectedValue));
onclicking the btnChat event:
<asp:Button ID="btnChat" Runat="server" CssClass="btn" OnClientClick="JavaScript:Open()" OnClick="btnChat_Click" Text="Join Room" />
The simple solution to your problem could be if you want to change your code...
//Javascript function
function Open()
{
var ddl = document.getElementbyId('<%= lstRooms.ClientID%>');
var ddlvalue = ddl.options[ddl.selectedIndex].value;
Window.Open("Chat.aspx?rid=" + ddlvalue );
}
remove all the code for JS in pageload and put this on aspx page.
let me know if it solves

adding multiple <asp:Hyperlink>s into a repeater

I have a repeater control, and I want to put an unknown number of <asp:Hyperlink>s into the template, for example if you start with this:
<asp:Repeater runat="server" ID="PetsRepeater">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "Owner")%>
<%#this.ListPets(Container.DataItem)%>
</ItemTemplate>
</asp:Repeater>
and in code behind:
public partial class test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PetOwner p = new PetOwner() {
Owner = "Jimmy",
PetNames = new List<String>() { "Nemo", "Dory" }
};
List<PetOwner> PetOwners = new List<PetOwner>() { p };
PetsRepeater.DataSource = PetOwners;
PetsRepeater.DataBind();
}
}
protected String ListPets(Object PetOwner)
{
StringBuilder sb = new StringBuilder();
foreach (String Name in ((PetOwner)PetOwner).PetNames)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(Name);
}
return sb.ToString();
}
}
class PetOwner
{
public String Owner;
public List<String> PetNames;
}
Now suppose instead of having the string "Nemo, Dory" in my repeater, I want something like this:
<asp:HyperLink runat=server Text="Nemo" NavigateUrl="Pet.aspx?Name=Nemo" />,
<asp:HyperLink runat=server Text="Dory" NavigateUrl="Pet.aspx?Name=Dory" />
How can I do that? I tried putting a foreach inline in the aspx page, but I get the error Invalid expression term 'foreach'.
If you need to have an asp:Hyperlink control, and not just a simple tag, you should use a nested repeater.
http://msdn.microsoft.com/en-us/library/aa478959.aspx

Categories