Pulling in a dynamic image in a control based on a url using C# and ASP.net - 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.

Related

Read XML and get data in ASP.net Web application

I need to find coSpaces total="3" value from the below XML in ASP.net C#. Please help me with the xmlreader code. I have seen other tutorial where I can find element value but not this type.
Thanks,
<?xml version="1.0"?>
<coSpaces total="3">
<coSpace id="0">
<name>A</name>
<autoGenerated>false</autoGenerated>
</coSpace>
<coSpace id="2">
<name>B</name>
<autoGenerated>false</autoGenerated>
</coSpace>
<coSpace id="4">
<name>C</name>
<autoGenerated>false</autoGenerated>
</coSpace>`
</coSpaces>
You can get total in this way:
private static string GetTotal()
{
var document = new XmlDocument();
using (var file = new FileStream("file.xml", FileMode.Open))
{
using (var reader = XmlReader.Create(file))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
var attr = reader["total"];
return attr;
}
}
}
}
return null;
}
Taking a minute to learn XPath, and the 2 methods that use it (SelectSingleNode, and SelectNodes) will really help in a lot of situations.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace testconsole
{
class Program
{
public static string strFileName = "c:\\temp\\test.xml";
static void Main(string[] args) {
XmlDocument xml = new XmlDocument();
xml.Load(strFileName);
XmlElement ndMatch = (XmlElement) xml.SelectSingleNode("//coSpaces[#total=3]");
if (ndMatch != null) {
foreach (XmlElement ndCoSpace in ndMatch.SelectNodes("coSpace")) {
Console.Write(ndCoSpace.GetAttribute("id"));
}
} else {
Console.Write("Not found in " + strFileName);
}
}
}
}

user.Roles.FirstOrDefault() returns DynamicProxy

OK...
I was finally making some headway with creating a User Management page using Identity 2 in Web Forms.
It was mostly moving along just fine. When suddenly I run into this issue, and it makes no sense to me.
I have an AS form with a dropdown list of Roles. That list is populated using
roleMgr.Roles.ToList();
Works Great
I use the user being edited Role to set the current selected value.
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
This WAS working like dynamite
Last week...
Now all of a sudden user.Roles.FirstOrDefault().ToString(); is returning
"System.Data.Entity.DynamicProxies.IdentityUserRole_FDDE5D267CF62D86904A3BC925D70DC410F12D5BE8313308EC89AC8537DC6375"
What he heck, man?
So I tried user.Roles.Take(1).ToString();
That returns
"System.Linq.Enumerable+d__24`1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole]"
I have to presume I Broke, Something...
But What?
Nothing in this code page changed at all between when it worked and then didn't.
The only thing I did related to Identity at all was Migrate a couple of fields into AspNetUsers (another whole ballgame, migrations...) which also worked like dynamite BTW.
I even went to the extreme of wiping out my Migrations and AspNet user tables entirely, and re-initializing it all.
Any suggestions ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Sperry_Parts.Models;
using Sperry_Parts.Logic;
using Microsoft.AspNet.Identity.Owin;
using Owin;
namespace Parts.Admin
{
public partial class CreateEditUser : System.Web.UI.Page
{
private bool NewUser
{
get { return ViewState["NewUser"] != null ? (bool)ViewState["NewUser"] : false; }
set { ViewState["NewUser"] = value; }
}
private string EditUser
{
get { return (string)ViewState["EditUser"]; }
set { ViewState["EditUser"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EditUser = Session["Edit_User"].ToString();
// Access the application context and create result variables.
Models.ApplicationDbContext context = new ApplicationDbContext();
RoleActions roleAction = new RoleActions();
// Create a RoleStore object by using the ApplicationDbContext object.
var roleStore = new RoleStore<IdentityRole>(context);
// Create a RoleManager object that is only allowed to contain IdentityRole objects.
var roleMgr = new RoleManager<IdentityRole>(roleStore);
// Load the DDL of Roles
var roles = roleMgr.Roles.ToList();
ddlUserType.DataTextField = "Name";
ddlUserType.DataValueField = "Id";
ddlUserType.DataSource = roles;
ddlUserType.DataBind();
if (EditUser == "")
{
txtUserName.Enabled = true;
txtUserName.Focus();
NewUser = true;
} // End New User
else
{
// User part
var userMgr = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
txtUserName.Enabled = false;
txtFullName.Focus();
var user = userMgr.FindByName(EditUser);
if (user != null)
{
txtUserName.Text = user.UserName;
txtUserEmail.Text = user.Email;
txtFullName.Text = user.FullName;
var hisroles = user.Roles.ToList(); // properly returns 1 item
// this is where it went off the rails - these 4 lines are debugging code
string xrole = user.Roles.FirstOrDefault().ToString();
string role2 = user.Roles.Take(1).ToString();
string trythis = xrole.ToString();
string trythis2 = role2.ToString();
// I swear, this worked last week...
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
}
} // End Editing User
} // End if (!IsPostBack)
} // End Page Load
protected void CreateUser()
{
// removed as non-relevant to question
} // End CreateUser
protected void UpdateUser()
{
// removed as non-relevant to question
} // End UpdateUser
protected void btnSave_Click(object sender, EventArgs e)
{
// removed as non-relevant to question
} // End btnSave
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/ManageUsers");
} // End btnCancel
} // End Class CreateEditUser
}
I ran into the same problem trying to set the value of a "Roles" DropDownList inside a GridView Control. I solved it by using:
user.Roles.First().RoleId
It just happens that my RoleId is also my role name.

ASP.NET NullReferenceException for get_Session()

public class MessageHelper : System.Web.UI.MasterPage
{
public MessageHelper()
{
}
public string Message
{
set { Session["Message"] = value; }
get
{
if (Session["Message"] != null)
{
var msg = Session["Message"] as string;
Session["Message"] = "";
return msg;
}
return "";
}
}
public string ErrorMsg
{
set { Session["Error"] = value; }
get
{
if (Session["Error"] != null)
{
var err = Session["Error"] as string;
Session["Error"] = "";
return err;
}
return "";
}
}
}
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.UI.UserControl.get_Session() +15
WebApplication1.MessageHelper.get_ErrorMsg() in ..file.master.cs:71
where line 71 is: if (Session["Error"] != null)
what am I doing wrong here?!
EDIT (transcribed from original author):
#David,
here is AdminMaster.master.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.SessionState;
namespace WebApplication1
{
public partial class AdminMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
MessageHelper msg = new MessageHelper();
if (msg.ErrorMsg != "")
{
// do something
}
if (msg.ErrorMsg != "")
{
// do something
}
}
}
public class MessageHelper : System.Web.UI.MasterPage
{
public MessageHelper()
{
}
public string Message
{
set { System.Web.HttpContext.Current.Session["Message"] = value; }
get
{
if (System.Web.HttpContext.Current.Session["Message"] != null)
{
var msg = System.Web.HttpContext.Current.Session["Message"] as string;
System.Web.HttpContext.Current.Session["Message"] = "";
return msg;
}
return "";
}
}
public string ErrorMsg
{
set { System.Web.HttpContext.Current.Session["Error"] = value; }
get
{
if (System.Web.HttpContext.Current.Session["Error"] != null)
{
var err = System.Web.HttpContext.Current.Session["Error"] as string;
System.Web.HttpContext.Current.Session["Error"] = "";
return err;
}
return "";
}
}
}
}
so it does inherit from System.Web.UI.MasterPage, my bad.
i want the MessageHelper to be accessed from different pages on the site. all of my pages use the Master file, that's why i put the MessageHelper in the master file.
what is wrong here?
During debugging, can you confirm that Session is not null? Try referencing it fully-qualified as System.Web.HttpContext.Current.Session within this class and see if that helps any.
Edit: In response to the non-answer answer that you posted...
It's not recommended to put that helper class in the same file as your master page. Put it in its own file named for the class. (There's probably debate over whether every class should have its own file, but in this particular case it's clear that the two classes in this one file are very much unrelated and shouldn't be together.)
The class can have its own namespace, such as WebApplication1.Helpers (though I recommend in the future using something more descriptive than WebApplication1, but don't try to change it here because it'll cause errors elsewhere in the project), and other class files can reference that namespace with using WebApplication1.Helpers in order to use that class.
Separating classes into an intuitive structure in the project (or multiple projects, as things grow in complexity) will make it easier to support in the future.
And, seeing the whole file, the helper class definitely should not inherit from MasterPage. It doesn't need to, and doing so adds things to that class that shouldn't be there.
I'm a bit confused by what you're trying to achieve with the MessageHelper class.
If it is code common to your master pages then you should surely be inheriting AdminMaster from MessageHelper.
eg.
public partial class AdminMaster : MessageHelper
If not, I don't understand why MessageHelper needs to inherit from MasterPage?

Hiding a link in 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();

SyndicationFeed: Content as CDATA?

I'm using .NET's SyndicationFeed to create RSS and ATOM feeds. Unfortunately, I need HTML content in the description element (the Content property of the SyndicationItem) and the formatter automatically encodes the HTML, but I'd rather have the entire description element wrapped in CDATA without encoding the HTML.
My (simple) code:
var feed = new SyndicationFeed("Title", "Description",
new Uri("http://someuri.com"));
var items = new List<SyndicationItem>();
var item = new SyndicationItem("Item Title", (string)null,
new Uri("http://someitemuri.com"));
item.Content = SyndicationContent.CreateHtmlContent("<b>Item Content</b>");
items.Add(item);
feed.Items = items;
Anybody an idea how I can do this using SyndicationFeed? My last resort is to "manually" create the XML for the feeds, but I'd rather use the built-in SyndicationFeed.
This worked for me:
public class CDataSyndicationContent : TextSyndicationContent
{
public CDataSyndicationContent(TextSyndicationContent content)
: base(content)
{}
protected override void WriteContentsTo(System.Xml.XmlWriter writer)
{
writer.WriteCData(Text);
}
}
then you can:
new CDataSyndicationContent(new TextSyndicationContent(content, TextSyndicationContentKind.Html))
For those for whom the solution provided by cpowers and WonderGrub also didn't work, you should check out the following SO question, because for me this question was actually the answer to my occurence of this problem!
Rss20FeedFormatter Ignores TextSyndicationContent type for SyndicationItem.Summary
Judging from the positive answer from thelsdj and Andy Rose and then later the 'negative' response from TimLeung and the alternative offered by WonderGrub I would estimate that the fix offered by cpowers stopped working in some later version of ASP.NET or something.
In any case the solution in the above SO article (derived from David Whitney's code) solved the problem with unwanted HTML encoding in CDATA blocks in an RSS 2.0 feed for me. I used it in an ASP.NET 4.0 WebForms application.
This should work.
item.Content = new TextSyndicationContent("<b>Item Content</b>",TextSyndicationContentKind.Html);
I had the same problem as some where the WriteContentsTo override wasn't being called in cpowers example (still no idea why). So, I changed it to inherit from the SyndicationContent class instead. Not sure if this is the best solution, but worked great in my situation.
public class CDataSyndicationContent : SyndicationContent
{
public CDataSyndicationContent(string content)
{
Text = content;
}
public override SyndicationContent Clone()
{
return new CDataSyndicationContent(Text);
}
public override string Type
{
get { return "html"; }
}
public string Text { get; private set; }
protected override void WriteContentsTo(XmlWriter writer)
{
writer.WriteCData(Text);
}
}
It might be too late but I leave my solution. I added it as a ElementExtension then it works for me. My environment is .NET 4.5.
XNamespace nsDefault = "http://www.w3.org/2005/Atom";
var content = new XElement(nsDefault + "content");
content.Add(new XCData("<b>Item Content</b>"));
item.ElementExtensions.Add(new SyndicationElementExtension(content));
try this
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = false;
//settings.ProhibitDtd = false;
using (XmlReader reader = XmlReader.Create(rssurl, settings))
Here is what we did :
public class XmlCDataWriter : XmlTextWriter
{
public XmlCDataWriter(TextWriter w): base(w){}
public XmlCDataWriter(Stream w, Encoding encoding): base(w, encoding){}
public XmlCDataWriter(string filename, Encoding encoding): base(filename, encoding){}
public override void WriteString(string text)
{
if (text.Contains("<"))
{
base.WriteCData(text);
}
else
{
base.WriteString(text);
}
}
}
And then to use the class :
public StringBuilder CDataOverwiriteMethod(Rss20FeedFormatter formatter)
{
var buffer = new StringBuilder();
//could be streamwriter as well
using (var stream = new StringWriter(buffer))
{
using (var writer = new XmlCDataWriter(stream))
{
var settings = new XmlWriterSettings() {Indent = true};
using (var xmlWriter = XmlWriter.Create(writer, settings))
{
formatter.WriteTo(xmlWriter);
}
}
}
return buffer;
}
The shortest way to do this is:
.Content = SyndicationContent.CreateXhtmlContent("<![CDATA[The <em>content</em>]]>")
That will be outputted in the XML as
<entry>
…
<content type="xhtml"><![CDATA[The <em>content</em>]]></content>
…
</entry>
Not an elegant solution, I admit, but it works properly – just tried on a project of mine.
try
item.Content = "<![CDATA[" +
SyndicationContent.CreateHtmlContent("<b>Item Content</b>") + "]]>";

Resources