Hiding a link in asp.net - asp.net

Duplicate:
Hiding a link in asp.net
Hi
this is the cs file of the masterpage...
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace LevoContactManagement
{
public partial class Default : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
BasePage page = (BasePage)Page;
if (page.CurrentUser != null)
{
lblCurrentUser.Text = "<strong>" + page.CurrentUser.FullName + "</strong> - " + page.CurrentUser.CompanyName;
if ((Session["CCFUser"] != null) && (bool.Parse(Session["CCFUser"].ToString()) == true))
{
ctrlLinkBar.AddLink("Issues Management", "AllIssues.aspx");
}
else
{
if (true) ctrlLinkBar.AddLink("Home", "Default.aspx");
if (page.CurrentUser.Permissions.Issues()) ctrlLinkBar.AddLink("Issues Management", "AllIssues.aspx");
if (page.CurrentUser.Permissions.Time()) ctrlLinkBar.AddLink( "Time Management", "TimeEntryForm.aspx");
if (page.CurrentUser.Permissions.Time()) ctrlLinkBar.AddLink("Time Filter", "TimeFilter.aspx");
if (page.CurrentUser.Permissions.SVN() && !(this.Page is _Default)) ctrlLinkBar.AddLink("SVN", "SVN.aspx");
if (true) ctrlLinkBar.AddLink("Profile", "ChangePassword.aspx");
if (page.CurrentUser.Permissions.Administration()) ctrlLinkBar.AddLink( "Administration", "Administration.aspx");
}
}
else lnkLogout.Visible = false;
}
protected void lnkLogout_Click(object sender, EventArgs e)
{
Session.Abandon();
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
}
}
i need to make the link Time Filter hidden.
the cs file of LinkBar is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebControlLib
{
[ToolboxData("<{0}:LinkBar runat=server></{0}:LinkBar>")]
public class LinkBar : WebControl
{
struct Link
{
public string Title;
public string URL;
public override string ToString()
{
return "<a href='" + URL + "'>" + Title + "</a>";
}
}
private bool m_bIsVertical = false;
private List<Link> m_Links = new List<Link>();
public bool IsVertical
{
get
{
return m_bIsVertical;
}
set
{
m_bIsVertical = value;
}
}
public void Clear()
{
m_Links.Clear();
}
public void AddLink(string Title, string URL)
{
Link lnk = new Link();
lnk.Title = Title;
lnk.URL = URL;
m_Links.Add(lnk);
}
protected override void RenderContents(HtmlTextWriter output)
{
List<string> items = new List<string>();
foreach (Link lnk in m_Links)
items.Add(lnk.ToString());
string sep = IsVertical ? "</td></tr><tr><td>" : " | ";
output.Write(
#"
<table width='100%' class='linkBar'>
<tr>
<td>" + string.Join(sep, items.ToArray()) + #"</td>
</tr>
</table>
");
}
}
}
how do i go about it? i changed the master.designer.cs file as follows-->
public partial class Default {
protected System.Web.UI.HtmlControls.HtmlForm form1;
protected System.Web.UI.WebControls.Label lblCurrentUser;
protected System.Web.UI.WebControls.LinkButton lnkLogout;
public WebControlLib.LinkBar ctrlLinkBar;
public System.Web.UI.WebControls.ContentPlaceHolder LeftNav;
protected System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1;
protected System.Web.UI.WebControls.ContentPlaceHolder BodyContent;
}
but the link still does not appear on the Design view of the masterpage, hence i cant find the id, therefore i cant hide it. What is an alternative to this?

I assume that you're talking about hiding the link to TimeEntryForm.aspx, and that you probably want to do this in only limited circumstances (which is why you don't want to just omit the line).
The link isn't actually in itself a control, so it won't have its own ID. It's a member of the List of links that belongs to the LinkBar control, and the LinkBar takes care of rendering them to the screen.
As you're adding these links to the LinkBar at run time, they won't display in the design view preview in Visual Studio - it will only display when you view the page in a browser.
I'd suggest that you get rid of the LinkBar, and just add the controls to the page as simple HyperLink controls. If you like, do this in the designer. Then you can set the visibility of each link in the code behind using the Visible property on those hyperlinks, like such:
hlTimeLink.Visible = page.CurrentUser.Permissions.Time();

Related

Xamarin.Forms page is not appearing immediately after another page has been popped

I have three pages at the moment in my app. I will call them EventsPage, NewEventPage, and ListPage. EventsPage is the first page of the app and you can open a NewEventPage from there. On this NewEventPage is a button that pops the NewEventPage from the stack and is supposed to create a ListPage immediately afterward, but the ListPage is not appearing, although I found out that its constructor is running.
Here's the code for the NewEventPage:
using Partylist.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Partylist.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NewEventPage : ContentPage
{
// Constructor.
public NewEventPage()
{
InitializeComponent();
}
// Event handlr for when the "Cancel" button is clicked.
async void OnCancelClicked(object sender, EventArgs e)
{
// Goes back to the previous page.
await Navigation.PopAsync();
}
// Event handler for when the "Create" button gets clicked.
async void OnCreateClicked(object sender, EventArgs e)
{
// Make sure there is something in the text entry.
if (string.IsNullOrWhiteSpace(EventNameEntry.Text))
{
// If there is nothing there, print an error message.
ErrorLabel.Text = "Your event needs a name!";
}
// If there is something in the text entry, try to create
// a new event with the text as its name.
else
{
// Variable to store the created event.
Event newEvent = new Event();
// Variable to store its folder.
DirectoryInfo newEventFolder;
// Flag to see if the event was created sccessfully.
bool eventCreated;
try
{
// If there's already an event with that name, let the
// user know.
if
(Directory.Exists(Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
EventNameEntry.Text)))
{
ErrorLabel.Text = "You already have an event with that name.";
eventCreated = false;
}
// Otherwise, try to creaate the folder.
else
{
newEventFolder = Directory.CreateDirectory(
Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
EventNameEntry.Text));
// Then, create the event based on that folder.
newEvent = new Event
{
FolderName = EventNameEntry.Text,
DateCreated = newEventFolder.CreationTime,
DateEdited = newEventFolder.LastWriteTime
};
// Get rid of any error messages that might be on screen.
ErrorLabel.Text = "";
eventCreated = true;
}
}
// Should throw an ArgumentException in most cases where there is
// an invalid character.
catch (ArgumentException)
{
// Get all the invalid characters and turn them into a string.
char[] invalidChars = Path.GetInvalidPathChars();
string invalid = "";
foreach(char currentChar in invalidChars)
{
invalid += currentChar;
}
// Change the text of the error label.
ErrorLabel.Text = "Your event name can't have these characters: \""
+ invalid + "\".";
eventCreated = false;
}
// If the event was created successfully, select it, pop the "New Event"
// page, and open a "List" page for the event.
if (eventCreated)
{
App.selectedEvent = newEvent;
await Navigation.PopAsync();
await Navigation.PushAsync(new ListsPage());
}
}
}
}
}
And here's the code for the ListPage:
using Partylist.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Partylist.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListsPage : ContentPage
{
// List of lists, used to populate
// the page's ListView (see the XAML).
public ObservableCollection<PartylistList> ListList { get; set; }
// Constructor.
public ListsPage()
{
// Does all the stuff to make the page
// exist that doesn't involve anything
// specific to this particular page in
// this particular app.
InitializeComponent();
}
// Override for OnAppearing().
protected override void OnAppearing()
{
// Regular OnAppearing() method.
base.OnAppearing();
// Set the title to be the name of the selected event.
Title = App.selectedEvent.FolderName;
// Set the BindingContext of the page to itself.
this.BindingContext = this;
// Set the ItemsSource of the ListView in the
// XAML to the ObservableCollection.
ListList = new ObservableCollection<PartylistList>();
ListListView.ItemsSource = ListList;
// Loop to populate the ObservableCollection.
for (int i = 0; i < Directory.GetFiles(
Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
App.selectedEvent.FolderName))
.Length; i++)
{
// Add a new list.
ListList.Add(new ContactList());
// Set the filename to the name of the file
// that the list corresponds to.
ListList.ElementAt(i).Filename =
Directory.GetFiles(
Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
App.selectedEvent.FolderName))[i];
// Sets the date/time created to the file's
// creation date.
ListList.ElementAt(i).DateCreated = Directory
.GetCreationTime(Directory.GetFiles(
Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
App.selectedEvent.FolderName))[i]);
// Sets the date/time last edited to the
// folder's write date.
ListList.ElementAt(i).DateEdited = Directory
.GetLastWriteTime(Directory.GetFiles(
Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
App.selectedEvent.FolderName))[i]);
}
}
}
}

Prevent Inserting same combination of Component and template :

In a page when we will click the component Presentation tab we can see the component and template listed there.On clicking of Insert button just below that, it will open another window "Insert component presentation" there also we will have Insert and close button.So now what i need to do While inserting i need to check whether the combination of selected Component and Template is already present there on page or not. If yes then it should prevent inserting the same with a popup like "this combination is already present, select other componet".
Any idea how can i proceed. How can i trigger a Javascript on the Insert button?
EDIT:
When i am subscrbing it to Page i am getting erro.My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using Tridion.ContentManager.Extensibility.Events;
using Tridion.ContentManager.Extensibility;
using Tridion.ContentManager.ContentManagement;
using System.IO;
using System.Windows.Forms;
namespace MyEventHandlers
{
[TcmExtension("MyEventHandlerExtension")]
public class MyEventHandler : TcmExtension
{
public MyEventHandler()
{
Subscribe();
}
public void Subscribe()
{
EventSystem.Subscribe<Page, SaveEventArgs>(SaveBtnInitiated, EventPhases.Initiated);
}
private void SaveBtnInitiated(Page subject, SaveEventArgs args, EventPhases phase)
{
try
{
List<string> allcplist = new List<string>();
List<string> allcplist = new List<string>();
foreach (ComponentPresentation cp in subject.ComponentPresentations)
{
allcplist.Add(cp.Component.Id + "," + cp.ComponentTemplate.Id);
}
List<string> uniquecplist = allcplist.Distinct().ToList();
if (allcplist.Count != uniquecplist.Count)
{
subject.Checkin(false);
throw new Exception("Page has duplicate component presentation");
}
catch(Exception)
{
}
}
You can implement this in an event handler that is subscribed to the Page Save event and the Initiated phase. When there is a duplicate Component Presentation you can cancel the Save by throwing an exception. The message will be shown in the Message Center in the TCM Explorer.
Why are you subscribing to the Component? I think it should be the Page. Then you can walk through the ComponentPresentations property.
Code to go through the Component Presentations and throw an exception when duplicate presentations are found:
foreach (var cpA in subject.ComponentPresentations)
{
if (subject.ComponentPresentations.Where(cpB => ComponentPresentationsAreEqual(cpA, cpB)).ToList().Count() > 2)
{
throw new DuplicateComponentPresentationsEmbeddedOnPageException();
}
}
And the function to include cpB in the list when it is equal to cpA:
function ComponentPresentationsAreEqual(ComponentPresentation cpA, ComponentPresentation cpB)
{
return cpA.Component.Id == cpB.Component.Id && cpA.ComponentTemplate.Id == cpB.ComponentTemplate.Id;
}
I got my Result with this code Thanks to #Arjen Stobbe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using Tridion.ContentManager.Extensibility.Events;
using Tridion.ContentManager.Extensibility;
using Tridion.ContentManager.ContentManagement;
using System.IO;
using System.Windows.Forms;
namespace MyEventHandlers
{
[TcmExtension("MyEventHandlerExtension")]
public class MyEventHandler : TcmExtension
{
public MyEventHandler()
{
Subscribe();
}
public void Subscribe()
{
EventSystem.Subscribe<Page, SaveEventArgs>(SaveBtnInitiated, EventPhases.Initiated);
}
private void SaveBtnInitiated(Page subject, SaveEventArgs args, EventPhases phase)
{
try
{
List<string> allcplist = new List<string>();
List<string> allcplist = new List<string>();
foreach (ComponentPresentation cp in subject.ComponentPresentations)
{
allcplist.Add(cp.Component.Id + "," + cp.ComponentTemplate.Id);
}
List<string> uniquecplist = allcplist.Distinct().ToList();
if (allcplist.Count != uniquecplist.Count)
{
subject.Save(false);
throw new Exception("Page has duplicate component presentation");
}
catch(Exception)
{
}
}
But i am not deleting the duplicate CP present on the page. Do i need to add,
for each()
inside
if (allcplist.Count != uniquecplist.Count)
{
}

Recursive function to going through each embedded schema field in a schema to reach a leaf data field

I have a schema in Tridion which have embedded schema fields which may further have embedded fields in there.
I want to reach final leaf field so that I can assign some value to it. For that I want to write recursive function which loop through each and every field until it reaches a final field.
I am implementing using the Core Service in SDL Tridion 2011
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;
using System.Net;
using System.Xml;
using Tridion.ContentManager.CoreService.Client;
using System.Text;
using Tridion.ContentManager.CoreService;
using System.ServiceModel.Channels;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Data.OleDb;
using System.Data;
using System.Configuration;
namespace Loading_Utility
{
public partial class TST : System.Web.UI.Page
{
Fields obj = new Fields();
protected void Page_Load(object sender, EventArgs e)
{
using (ChannelFactory<ISessionAwareCoreService> factory =
new ChannelFactory<ISessionAwareCoreService>("wsHttp_2011"))
{
ISessionAwareCoreService client = factory.CreateChannel();
var schemaFields = client.ReadSchemaFields("tcm:202-2242-8", true, new ReadOptions());
ComponentData component = (ComponentData)client.GetDefaultData(ItemType.Component, "tcm:202-638-2");
var fields = Fields.ForContentOf(schemaFields);
component.Schema.IdRef="tcm:202-2242-8";
}
}
public void fieldRecursion(Field field)
{
//var getFields = fields;
if (field.GetType() == typeof(EmbeddedSchemaFieldDefinitionData))
{
// code for checking further if field is embedded or not
//Field newField = field.GetSubFields().GetFieldElements( new ItemFieldDefinitionData() as Field)
//fieldRecursion(recursiveField);
}
//string fieldName = recursiveField.Name;
//fields[fieldName] = "HI";
}
}
}
Whilst I don't have the solution you are looking for, I see you're using the core service, personally I prefer to get hold of the Component XML (Component.Content) and parse/manipulate it as I need. Perhaps if you can paste the XML here I can drop it into one of my sample core service projects and send you a solution back?
In the event that doesn't help you, i've had a look at the api, and this should help you get going in the right path. Perhaps once you have a solution you could paste it here?
public void RecurseEmbeddedFields(SchemaFieldsData schemaFields)
{
foreach (ItemFieldDefinitionData field in schemaFields.Fields)
{
if (field.GetType() == typeof(EmbeddedSchemaFieldDefinitionData))
{
// check if this field contains more embedded fields
// if it does recurse
}
}
}
OK, I felt a bit guilty about not helping, but I still stand by my view that this is not a Tridion-related question and that you should try getting some more experience with general development practices.
Here's an example of how to load the Component's content, then read it recursively using Xml:
Xml of the component:
<Content xmlns="uuid:02395f72-acef-44e8-9c35-ff8c9f380251">
<EmbeddedSchema1>
<SomeField>Hello</SomeField>
<EmbeddedSchema2>
<ATextField>There</ATextField>
</EmbeddedSchema2>
</EmbeddedSchema1>
</Content>
Core Service code:
static void Main(string[] args)
{
SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("wsHttp_2011");
ReadOptions readOptions = new ReadOptions();
ComponentData component = (ComponentData)client.Read("tcm:5-3234", readOptions);
Console.WriteLine("Find fields recursively");
XmlDocument content = new XmlDocument();
content.LoadXml(component.Content);
SchemaData schema = (SchemaData)client.Read(component.Schema.IdRef, readOptions);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("content", schema.NamespaceUri);
foreach (XmlElement node in content.SelectNodes("content:*", ns))
{
ReadContentRecursively(node, ns);
}
client.Close();
}
private static void ReadContentRecursively(XmlElement node, XmlNamespaceManager ns)
{
if(!string.IsNullOrEmpty(node.InnerText))
{
foreach (XmlNode innerNode in node)
{
if(innerNode is XmlText)
{
Console.WriteLine("Node " + node.Name + " with value \"" + innerNode.Value + "\"");
}
}
}
if(node.SelectNodes("content:*", ns).Count > 0)
{
foreach (XmlElement childNode in node.SelectNodes("content:*", ns))
{
Console.WriteLine("Found Field: " + childNode.Name);
ReadContentRecursively(childNode, ns);
}
}
}
Notice how ReadContentRecursively calls itself?
Hope this helps.

Hidden Field altered through javascript not persisting on postback

I have a web user control with a hidden field on it. When a javascript event (click) ocurrs, I am trying to set a value in the hidden field, so that the value can be retained on postback and remembered for the next rendering. The control is a collapsible panel extender that does not cause postback, uses jquery, and if postback occurs elsewhere on the page, it remembers if it is expanded or collapsed.
The problem is that the javascript executes, but does not actually change the value in the hidden field. If I use the dom explorer, the hidden fiend is still set to the default, and then when I debug, in the the next postback the hidden field is still set to the default as well.
I have also tried using the tried and true getElementById with no success.
No javascript errors occur.
ASCX code:
<input id="hiddenCurrentState" type="hidden" runat="server" />
Codebehind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class Controls_SubControls_CollapsiblePanelExtender : System.Web.UI.UserControl
{
public string HeaderControlId { get; set; }
public string BodyControlId { get; set; }
public string CollapseAllControlId { get; set; }
public string ShowAllControlId { get; set; }
public CollapsedState DefaultState { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
hiddenCurrentState.Value = DefaultState.ToString();
}
}
protected override void OnPreRender(EventArgs e)
{
BuildJQueryScript();
base.OnPreRender(e);
}
private void BuildJQueryScript()
{
StringBuilder script = new StringBuilder();
script.Append("$(document).ready(function(){\n");
//toggle based on current state
script.Append("if ($(\"#" + hiddenCurrentState.ClientID + "\").attr(\"value\")==\"Expanded\")\n");
script.Append("{\n");
script.Append("$(\"#" + BodyControlId + "\").show();\n");
script.Append("$(\"#" + hiddenCurrentState.ClientID + "\").val(\"Expanded\");\n");
script.Append("}\n");
script.Append("else\n");
script.Append("{\n");
script.Append("$(\"#" + BodyControlId + "\").hide();\n");
script.Append("$(\"#" + hiddenCurrentState.ClientID + "\").val(\"Collapsed\");\n");
script.Append("}\n");
//toggle on click
script.Append("$(\"#" + HeaderControlId + "\").click(function(){\n");
script.Append(" $(this).next(\"#" + BodyControlId + "\").slideToggle(500)\n");
script.Append(" return false;\n");
script.Append("});\n");
//collapse all
if (!String.IsNullOrEmpty(CollapseAllControlId))
{
script.Append("$(\"#" + CollapseAllControlId + "\").click(function(){\n");
script.Append(" $(\"#" + BodyControlId + "\").slideUp(500)\n");
script.Append(" return false;\n");
script.Append("});\n");
}
//show all
if (!String.IsNullOrEmpty(ShowAllControlId))
{
script.Append("$(\"#" + ShowAllControlId + "\").click(function(){\n");
script.Append(" $(this).hide()\n");
script.Append(" $(\"#" + BodyControlId + "\").slideDown()\n");
//script.Append(" $(\".message_list li:gt(4)\").slideDown()\n");
script.Append(" return false;\n");
script.Append("});\n");
}
script.Append("});\n");
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CollapsiblePanelScript", script.ToString(), true);
}
}
public enum CollapsedState
{
Expanded = 0,
Collapsed = 1
}
I don't see where you are setting the value of the hidden field on the client side. I would expect to see a line something like the following in your collapse/show functions to actually change the value on the client when the panel is collapsed/expanded.
Collapse:
script.Append( " $(\"#" + hiddenCurrentState.ClientID + "\").val(1);\n" );
Show:
script.Append( " $(\"#" + hiddenCurrentState.ClientID + "\").val(0);\n" );
On every post back the entire page is rendered again, any values changed on the client side will not be persisted.
I recommend you store the state in a cookie. As you are using jQuery, the COOKIE library makes this a cinch.
Have you tried using <asp:HiddenField> instead of <input>?

Pulling in a dynamic image in a control based on a url using C# and ASP.net

I know this is a dumb question. For some reason my mind is blank on this. Any ideas?
Sorry should have been more clear.
Using a HtmlGenericControl to pull in link description as well as image.
private void InternalCreateChildControls()
{
if (this.DataItem != null && this.Relationships.Count > 0)
{
HtmlGenericControl fieldset = new HtmlGenericControl("fieldset");
this.Controls.Add(fieldset);
HtmlGenericControl legend = new HtmlGenericControl("legend");
legend.InnerText = this.Caption;
fieldset.Controls.Add(legend);
HtmlGenericControl listControl = new HtmlGenericControl("ul");
fieldset.Controls.Add(listControl);
for (int i = 0; i < this.Relationships.Count; i++)
{
CatalogRelationshipsDataSet.CatalogRelationship relationship =
this.Relationships[i];
HtmlGenericControl listItem = new HtmlGenericControl("li");
listControl.Controls.Add(listItem);
RelatedItemsContainer container = new RelatedItemsContainer(relationship);
listItem.Controls.Add(container);
Image Image = new Image();
Image.ImageUrl = relationship.DisplayName;
LinkButton link = new LinkButton();
link.Text = relationship.DisplayName;
///ToDO Add Image or Image and description
link.CommandName = "Redirect";
container.Controls.Add(link);
}
}
}
Not asking anyone to do this for me just a reference or an idea.
Thanks -overly frustrated and feeling humbled.
I'm assuming you want to generate an image dynamicly based upon an url.
What I typically do is a create a very lightweight HTTPHandler to serve the images:
using System;
using System.Web;
namespace Example
{
public class GetImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString("id") != null)
{
// Code that uses System.Drawing to construct the image
// ...
context.Response.ContentType = "image/pjpeg";
context.Response.BinaryWrite(Image);
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You can reference this directly in your img tag:
<img src="GetImage.ashx?id=111"/>
Or, you could even create a server control that does it for you:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Example.WebControl
{
[ToolboxData("<{0}:DynamicImageCreator runat=server></{0}:DynamicImageCreator>")]
public class DynamicImageCreator : Control
{
public int Id
{
get
{
if (ViewState["Id" + this.ID] == null)
return 0;
else
return ViewState["Id"];
}
set
{
ViewState["Id" + this.ID] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("<img src='getImage.ashx?id=" + this.Id + "'/>");
base.RenderContents(output);
}
}
}
This could be used like
<cc:DDynamicImageCreator id="db1" Id="123" runat="server/>
Check out the new DynamicImage control released in CodePlex by the ASP.NET team.
This is kind of a horrible question. I mean, .NET has an image control where you can set the source to anything you want. I'm not sure what you're wanting to be discussed.

Resources