Working with resources - asp.net

there!
I'm working with asp.net 3.5 web-site. And I have such problem:
I have 3 aspx pages, that contain asp:Label control with name "LabelContent" and foreach page I have two resx files, that contain LabelContentResource.Text and LabelContent binds LabelContentResource to , for 2 cultures. Also I have content editing page. On this page admin choses page for edit and in WYSIWG editor I need to load appropriate resorce. Like so:
string pageForLoadName = "links.aspx.de-AT.resx";
string key ="LabelContent.Text";
string resValue= LoadREsource(pageForLoadName ,key );
How can I write LoadREsource fnction?
Thanks!

Something along the lines of
public string LoadResource(string pageForLoadName,string key)
{
return (String)HttpContext.GetGlobalResourceObject(pageForLoadName, key);
}
Also, don't think you need pageForLoadName = "links.aspx.de-AT.resx";
just pageForLoadName = "links.aspx.de-AT";

Related

ASP.NET -> How to POST data to the form such that images are displayed

Scenario : ASP.NET site has a page named ShowDesign.aspx.
ASPX page has lot of controls. I have a DIV tag and I load the images in code behind. DIV is defined something like below in the ASPX.
<div id="pImageHolder" runat="server"></div>
Below is the code behind that loads images.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Loop inside PreviewImages which has lots of images.
foreach (String imgFile in this.PreviewImages)
{
Image pImage = new Image();
pImage.ImageUrl = imgFile; //URL length is longer. Do something.
this.pImageHolder.Controls.Add(pImage);
}
}
Update : Jun 1,2012 -> I have updated this question with more clarity as to what I am trying to do.
In OnInit(), I get the URL of the image (in the above loop). Every image will have unique URL.
Since the URL length of every image is longer, it doesn't display. The solution to this issue seems to be POSTING data to the form. The data that needs to be POSTED will be the URL contents.
The URL contains lot of '&' and I need to submit the contents of each '&' to the form.
Don't know if I need to use AJAX or Jquery here.
I need some help here to achieve the above.
Hope my question is clear. If not, please let me know.
According to latest comments, this question history and at the end you want post data to another url and get response html. Try this (I snipped your original url from previous question since is really big):
string strangeUrl = "http://example.com/is/m//company1/Rec-Sc-105-QL2?setAttr.safe={visible=false}&setAttr.insertedTextPlaceholder={visible=false}";
string data = strangeUrl.Substring(strangeUrl.IndexOf("?") + 1);
WebClient wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string result = wc.UploadString("www.example.com/addres-for-post.aspx", data);

How to get Links on a web-page using C#?

I do have an problem in C# that is
Suppose there is one website's link....www.xyz.comand suppose there are 25 links on the website's home page.
Now i want that using C# and asp.net i do have an String array suppose LinkArray[n] and TabArray[n] {string array} and i want that there should be a program which
can list all the links in the array as follows.
suppose links are :
Home
etc
Now i want that in two arrays it should be stored as
TabArray[2]= {Home,Contact}
LinkArray[2]={xyz.com/home.html,xyz.com/contact.html}
Likewise i want that i can get listed all the links details in of any web page.
Please suggest me some code/ guide tutorials
Thanks
You could use sharp-query or Html Agility Pack to parse HTML. Here's an example with sharp-query:
using System;
using XCSS3SE;
class Program
{
static void Main()
{
var sq = new SharpQuery("http://stackoverflow.com");
foreach (var el in sq.Find("a[href]"))
{
Console.WriteLine("{0} : {1}", el.InnerText, el.Attributes["href"].Value);
}
}
}

SEO URL rewriting ASP.NET

I already have an ASP.NET Web Site
I want to change my site to be more SEO url friendly.
I want to change ex. this site:
www.mydomain.aspx?articleID=5
to:
www.mydomain/article/learningURLrewrite
- articlename needs to be read from DB
How do I accomplish this?
I have already tried with some articles from Google which mentions IhttpModule without any luck.
My goal is to have a class responsible for redirecting based on folderpath(like this):
string folderpath = "my folderpath" (could be articles, products etc.)
string id = Request.QueryString["id"].ToString();
if(folderpath.equals("articles"))
{
string name = //find name from id in DB
//redirect user to www.mydomain/article/name
}
if(folderpath.equals("products"))
{
string name = //find name from id in DB
//redirect user to www.mydomain/products/name
}
Also I want to remove the aspx extension
You can use routing with ASP.NET WebForms too.
The steps are:
Add the route (or routes) at application start.
//In Global.asax
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("My Routename", "{*name}", "~/Article.aspx");
}
Create the Article.aspx as a normal webform
In the code for Article.aspx, you can access the url path like this:
public void Page_Load(object sender, EventArgs e)
{
var thePath = RouteData.Values["name"];
// Lookup the path in the database...
}
This posting tells you exactly how to use asp.net 4's routing engine - give it a whirl - if you have a specific problem in implementing it let us know.
http://weblogs.asp.net/dotnetstories/archive/2011/01/03/routing-in-asp-net-4-0-web-forms.aspx
Since you need specific parameter usage, you can define the parameters to get sent to your page. For that see:
http://msdn.microsoft.com/en-us/library/cc668177.aspx
and
How to: Access URL Parameters in a Routed Page
If you are using ASP.NET 4, then you should look into URL Routing. You would end up setting up custom routes like so:
routes.MapPageRoute(
"View Article", // Route name
"Articles/{*ArticleName}", // Route URL
"~/Articles.aspx" // Web page to handle route
);
And you write out the new links like so:
Page.GetRouteUrl("View Article", new { ArticleName= NAMEFROMDATABASE });
Unfortunately I won't give you a summary of how to build your entire site, but 2 really good places to start are an article by Scott Gu, and one on 4 Guys.
If you are using .net 3.5 or less then you can use these
http://urlrewriting.net
http://urlrewriter.net
I use the second one, in all my projects made in .net 3.5
if using .net 4.0 then you can do these
URL routing ( I think it does not support sub domain rewriting)
URL Rewrite 2.0 ( works with IIS 7 only)
UPDATE
Add these lines below the appSettings tag
<rewriter configSource="URLRewriter.config"/>
Then create separate file named as URLRewriter.config
And in that you can write like this (Add processing stop for the files not to be rewritten i.e images and js, etc)
<rewrite url="^(/.+(\.gif|\.png|\.jpg|\.ico|\.pdf|\.css|\.js|\.flv|\.eot|\.svg|\.ttf|\.woff|\.txt|\.doc|\.docx|\.pdf|\.xls|\.xlsx|\.xml)(\?.+)?)$" to="$1" processing="stop" />
<rewrite url="~/article/([^/.]+)" to="~/articledetail.aspx?articlename=$1" />
Then you would get the article name in the query string like this
string articlename = Request.QueryString["articlename"];
And the menu or other location of the site where you want to put the link to article, you can add an the AppSettings so that later on if you want to change the url pattern you can change it easily from the configs only,
<add key ="ArticalDetailsURL" value="/article/{0}" />
Then, in the page you can do like this
string articleName = "TestArticle";
lnkMenuLink.NavigateUrl = string.Format(ConfigurationSettings.AppSettings["ArticalDetailsURL"], articleName);
Thanks and Regards,
Harsh Baid

What's the best way to show a random image in ASP.NET?

What I am talking about is like this website :
http://www.ernesthemingwaycollection.com
It has a static wallpaper and a set of images that change from page to page, I want to implement a similar way of displaying random images from a set of images using ASP.NET.
EDIT : I want the image to stay the same in a session, and change from a session to another.
The site you mentioned is not using a random set of images. They are coded into the html side of the aspx page.
You could place an asp Image control on your page. Then on the page's Page_Load function set the image to a random picture of your set.
protected void Page_Load(object sender, EventArgs e)
{
this.Image1.ImageUrl = "~/images/random3.jpg";
}
You have different options on where to store the image set data. You could use a database and store the urls in a table. This would allow to use the built-in Random function found in SQL. Or you can save a XML file to the server, load that then use the Random .Net class to pick one of your xml nodes.
Personally i would recommend the Database solution.
EDIT: Because the server session is destroyed after 20mins you may want to look at using cookies so you can see the last random image they saw.
If you just want to rotate a set number of images you could use the ASP.NET AdRotator control (at last, a use for it!).
If you want to do something fancier, considering using a jQuery slideshow such jQuery Cycle Plugin. There is also a slideshow control in the AjaxControlToolkit, which is easy to integrate.
string imageDir = "/images/banner/";
public static string chooseImage(string imageDir)
{
string[] dirs = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/" + imageDir + "/"), "*.*");
Random RandString = new Random();
string fileFullPath = dirs[RandString.Next(0, dirs.Length)];
// Do not show Thumbs.db ---
string fileName = string.Empty;
do
{
fileName = System.IO.Path.GetFileName(fileFullPath);
} while (fileName.Contains(".db"));
string imgPath = "/images/" + imageDir + "/" + fileName;
return imgPath;
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}

Read in a html page within asp.net mvc

i am porting over a website from asp.
i have one page that i can't figure out how to migrate it.
The page is dynamic in the sense that it reads in other html pages and sticks the content into the main "container" page. In the middle of the asp page it has sections like below
<%
Dim fso1, f11, ts1, s1
Const ForReading1 = 1
Set fso1 = CreateObject("Scripting.FileSystemObject")
Set ts1 = fso1.OpenTextFile("" & Server.MapPath("newsletters/welcome.html") & "", ForReading)
s1 = ts1.ReadAll
Response.Write s1
ts1.Close
set fso1 = nothing
set f11 = nothing
set ts1 = nothing
set s1 = nothing
%>
Any suggestions in ASP.net MVC for best way to read in other html pages and stick them into a page view.
I assume that these are HTML fragments, not full pages. You could convert them to partial views -- pretty trivial, you just add the correct page directive and rename to .ascx. Then you would use Html.RenderPartial to include the partial in your main view. Another way would be to create your own HtmlHelper extension that works like RenderPartial but simply reads the named file and writes it to the response just like you are currently doing.
Ex1:
<% Html.RenderPartial( "welcome.ascx" ); %>
Ex2:
<% Html.RenderHtml( Server.MapPath( "newletters/welcome.html" ) ); %>
Note that in the first case the view file needs to live in the Views directory. In the second case, you can reference the file from anywhere that the worker process has read access. You'll need to create the second method yourself. Perhaps something similar to:
public static class MyHtmlHelperExtensions
{
public static void RenderHtml( this HtmlHelper helper, string path )
{
var reader = new StreamReader( path );
var contents = reader.ReadToEnd();
helper.ViewContext.HttpContext.Response.Write( contents );
}
}
Please note that you'll have to add error handling.
To read the contents of a text file in .Net, use the File.ReadAllText method.
The exact equivalent of your code snippet would be
<%= File.ReadAllText(Server.MapPath("newsletters/welcome.html")) %>
You should write like this:
string html = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/htm/external/header.htm"));

Resources