httphandler return into string variable - c#

I have an httphandler that returns a string (a part description).
I'd like to use the return value in a title attribute on an image, which will be updated on a page load.
I have the following code in page_load event...
imgThumbnail.Attributes.Add("title", "~/Views/Admin/ImageRepository/ShowDescription.ashx?partno=123456&view=thumb");
I'm not sure how to get the title text to be the return value instead of just "~/Views/Admin/ImageRepository/ShowDescription.ashx?partno=123456&view=thumb".
How can I do this? This is the first time using an http handler. I have tested the handler and it does return the string I expect it to.

I think you might have to rethink how you are approaching this, your code might look like this:
string imgTitle = "Image Title"; // you need to set the value of imgTitle here.
imgThumbnail.Attributes.Add("title", imgTitle);
This might give an output like this:
<img title="Image Title" />
You probably don't want a handler for this, essentially, you could move the code from your handler to your page.
string imgTitle = GetImageTitle(partno); // you need to set the value of imgTitle here.
imgThumbnail.Attributes.Add("title", imgTitle);
public string GetImageTitle(string partno)
{
// put code to return image title here;
}
PS are you sure you don't want the alt attribute, <img> doesn't have a title attribute.

Related

C# ASP.Net Errors on form submission

I was hoping to get some insight on the error that are produced by the system. I am using a already built message system that I got some time ago and it works but sometimes on the forms I will get errors that I do not understand. For instance on a Create I have a try / catch block that produces a message if it has successfully Executed. I have tried to search for these errors in my project and it does not come up with anything. Even if it was in meta data a search should find it.
I use System.Text.StringBuilder sb = new System.Text.StringBuilder(); for the message and the code looks like this:
public ActionResult Create(Vendors model)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
if (ModelState.IsValid)
{
var userId = User.Identity.GetUserId();
//var getdata = ExtendedViewModels.VendorToEntity(model);
model.VendorId = Guid.NewGuid();
model.CreatedDate = System.DateTime.Now;
model.CreatedBy = User.Identity.Name;
model.Status = true;
db.Vendors.Add(model);
db.SaveChanges();
sb.Append("Submitted");
return Content(sb.ToString());
}
else
{
foreach (var key in this.ViewData.ModelState.Keys)
{
foreach (var err in this.ViewData.ModelState[key].Errors)
{
sb.Append(err.ErrorMessage + "<br/>");
}
}
}
}
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}
When this returns or closes the Modal it produces a message or if there is an error it will produce that so you can fix it like a Required field. If everything is okay it will produce from this:
#Html.StarkAjaxFormSubmiter("frmVendors", "tbVendors", true, "Action Successfully Executed")
This is a green box that shows up as "Action Successfully Executed". If something is wrong a red box shows up and you get a message. In my case I am getting a red box that says Submitted Read Warnings Alerts This is how it is spelled. I doubt this is a error that comes from ASP.Net it looks more like a custom message, I dont know what it means and I cannot find it anywhere. Regardless, it does create the record in the db. The other error I have gotten shows Something is went wrong [object, object] Not only do I want to find out what these mean, I also want to clean them up and give a proper message that makes sense. Does anyone have any ideas as to how to correct this? Could they be encypted in the custom package that was written for this? That is why I cannot find them. I have also viewed the package and did not find anything for this.
This is from Meta data:
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage);
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
//
// AfterSuccessCode:
// Add other JQuery code if you want
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage, string AfterSuccessCode);
Thanks for our help
UPDATE:
I did some searching on the web and found a program called JetBrains dotPeek. I decompiled the dll and sure enough the messages are in there. So I should be able to change them and recompile it and add if I want, to it.
I was not able to edit the decompiled dll. So I decided to just create a class in the main project and copy the the code to that class. Changing what I needed. Where my trouble was, was with misspellings. The dll used Sumitted as the sb.Append("Sumitted") I changed that in the controller to be Submitted. So the dll did not find "Sumitted" in the action, and in the dll class there is an If statement that faults to error if not found - which was listed as Read Warnings Error. I changed that and fixed all the misspellings. I also got rid of the Something is went wrong and changed it to something more meaningful. I will continue to add to this to give more meaningful messages. It helps to know what the error is, instead of [object], [object]. I dont know if this will help others, maybe if they have downloaded the same code I have and have issues.

GeneralLink in Sitecore

I'm new to Sitecore.. I have created a Page template and add a field for a URL of type General Link. I have created another field for the text for the link (this is standard practice in this project).
I simply want to display the link in my user control but I just cant get it to work. This should be simple but Im going round in circles
Here's an example of the code I've tried ..
ascx :
<asp:HyperLink runat="server" ID="lnkMain"></asp:HyperLink>
ascx.cs:
lnkMain.NavigateUrl = SiteCore.Context.Item.GetGeneralLink("Link1");
lnkMain.Text = item.GetFieldValue("Link1Text");
You should be careful using linkField.Url since it it will incorrectly render internal links to Sitecore Items and Media. You should instead be using Sitecore.Links.LinkManager.GetItemUrl(item) and Sitecore.Resources.Media.MediaManager.GetMediaUrl(item) for those.
It would be better to have a helper (extension) method to return the correct url for you, based on the type of link. Take a look this Sitecore Links with LinkManager and MediaManager blog post which has the correct code you need for this.
For reference:
public static String LinkUrl(this Sitecore.Data.Fields.LinkField lf)
{
switch (lf.LinkType.ToLower())
{
  case "internal":
    // Use LinkMananger for internal links, if link is not empty
    return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty;
  case "media":
    // Use MediaManager for media links, if link is not empty
    return lf.TargetItem != null ? Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem) : string.Empty;
  case "external":
    // Just return external links
    return lf.Url;
  case "anchor":
    // Prefix anchor link with # if link if not empty
    return !string.IsNullOrEmpty(lf.Anchor) ? "#" + lf.Anchor : string.Empty;
  case "mailto":
    // Just return mailto link
    return lf.Url;
  case "javascript":
    // Just return javascript
    return lf.Url;
  default:
    // Just please the compiler, this
    // condition will never be met
    return lf.Url;
}
}
Usage:
Sitecore.Data.Fields.LinkField linkField = item.Fields["Link1"];
lnkMain.NavigateUrl = linkField.LinkUrl();
It would be best of course to use <sc:FieldRender> control and let Sitecore handle it for you, but it looks like you do not have that option.
As of Sitecore 7.2 there is an alternative to linkField.Url:
Sitecore.Data.Fields.LinkField linkField = item.Fields["Link1"];
lnkMain.NavigateUrl = linkfield.GetFriendlyUrl();
A new LinkField.GetFriendlyUrl() method has been introduced. The method makes it easy to output a valid URL no matter what type of link the field contains. For internal links, the method returns a URL from LinkManager.GetItemUrl(). For media links, the method returns a URL from MediaManager.GetMediaUrl(). For external links, anchor links, e-mail links, and JavaScript links, the method returns the value of the LinkField.Url property. (400051)
http://techitpro.com/uncategorized/sitecore-7-2-changes/
It'd be easier if you use the Link control:
<sc:Link Field="Link1" runat="server" ID="link">
<sc:Text Field="Link1Text" runat="server" ID="linkText" />
</sc:Link>
That way, you don't have to do any code-behind stuff and you'll be able to use the Page Editor as well.
You can use below
<sc:Link ID="scLink" runat="server" Field="Your Link Field Name">
<sc:FieldRenderer ID="frTest" runat="server" FieldName="Your Text Field Name" />
</sc:Link>
It will work for you.
When you assign a value to a GeneralLink field of an item there is a field labeled "Link Description" in the Internal Link dialog that pops up. Fill in that value then use:
<sc:Link runat="server" Field="{YourFieldName}" />
That's it. Everything is "wired-up" for you, auto-magically.
You need to get the Linkfield value of the item and than get the LinkField type of that item. This will give you the type of link either an "Internal", "external", "mailto" and based on that can get the url of the link field as this is mentioned by #jammykam.
Same thing you can do to retrieve the LinkText as well.
For Reference :
public static string GetGeneralLinkText(LinkField link)
{
text = "";
if (link == null)
return false;
if (!string.IsNullOrEmpty(link.Text))
{
text = link.Text;
return true;
}
switch (link.LinkType)
{
case "internal":
if (link.TargetItem == null)
return false;
text = link["Text Field Name"];
break;
case "external":
case "mailto":
case "anchor":
case "javascript":
text = link.Text;
break;
case "media":
if (link.TargetItem == null)
return false;
Sitecore.Data.Items.MediaItem media = new Sitecore.Data.Items.MediaItem(link.TargetItem);
text = media.Name;
break;
case "":
break;
default:
return "";
}
return link["Text Field Name"];
}

Regular Expression to avoid HTML tags and empty values

I have applied a textbox click validation and wanted to avoid any html tags in text box also the simple < (open tag) and >(close tag). The below code is working for but i want to add additional validations also for empty strings and other tags in html. Can some one please help modify the regex for the requirement.
function htmlValidation()
{
var re = /(<([^>]+)>)/gi;
if (document.getElementById(’<%=TextBox2.ClientID%>’).value.match(re)){ document.getElementById(’<%=TextBox2.ClientID%>’).value = “”;
return false;
}
return true;
}
Corrected Code above
In my opinion, I believe you'll have a good hard work if you want to validate such things.
Instead of preventing HTML content in a text box, other solution could be just html entity encode Text property, so <p>a</p> would be converted to >p<a>p<.
Result of that is you're going to render the HTML "as text" instead of getting it interpreted by Web browser.
Check this MSDN article:
http://msdn.microsoft.com/en-us/library/73z22y6h(v=vs.110).aspx
$("#<%= btnAdd.ClientID %>").click(function () {
var txt = $("#<%= txtBox1.ClientID %>");
var svc = $(txt).val(); //Its Let you know the textbox's value
var re = /(<([^>]+)>)/gi;
if(txt.val()!=""){
if (!txt.val().match(re)) {
//my Operations
//goes here
});
return false;
}
else {
alert("Invalid Content");
}
}
else {
alert("Blank value selected");
}
I have used Jquery function to check for regular expresion. This question is a linked question with
Using Jquery to add items in Listbox from Textbox
Now i can mark this as my final answer.

C# String Property and string literal concatenation issue

I am a bit new at C# and I have run into a string concatenation issue. I am hoping someone might be able to give me a hint and help me resolve this. I have searched Google extensively and have spent more than a week on this so any help/advice would be greatly appreciated.
I have created a custom PathEditor for a string property. The property basically allows the user to key in a file to use in the app. If the file typed in is correct, it shows in the property cell as it should. What I am trying to do is output to the property cell an error message if the file typed in does not exist - I check this in my file validator. Here is the string literal issue.
If I use:
return inputFile+"Error_";
this works OK and I get the outpur file123.txtError_ in the property grid cell.
If I use:
return "Error_"+inputFile;
I get only the inputFile without the literal "Error_". Sot he property grid cell shows file123.txt in the property grid cell.
I have checked and inputFile is a string type. Any ideas as to why this is happening?
Also, is there any way to change to font, and/or, color of the message output? I tried to change the background of the property grid cell and I understand that this is not possible to do.
Thank you.
Z
More of the code:
[
Description("Enter or select the wave file. If no extension, or a non .wav extension, is specified, the default extension .wav will be added to the filename."),
GridCategory("Sound"),
Gui.Design.DisplayName ("Input Sound"),
PathEditor.OfdParamsAttribute("Wave files (*.wav)|*.wav", "Select Audio File"),
Editor(typeof(PathEditor), typeof(System.Drawing.Design.UITypeEditor))
]
public string InputWavefile
{
get { return System.IO.Path.GetFileName(inputtWavefile); }
set
{
if (value != inputWavefile) // inputWavefile has been changed
{
// validate the input stringg
_inputWavefile = FileValidation.ValidateFile(value);
// assign validated value
inputWavefile = _inputWavefile;
}
}
}
My guess is that you've got a funky character at the start of inputFile which is confusing things - try looking at it in the debugger using inputFile.ToCharArray() to get an array of characters.
The string concatenation itself should be fine - it's how the value is being interpreted which is the problem, I suspect...
I'm guessing your filename looks something like this, C:\Folder\FileName.txt when you start out.
In your FileValidation.ValidateFile() method you
return "Error_" + InputFileName;
it now looks like this: Error_C:\Folder\FileName.txt.
So, when you run the line below,
get { return System.IO.Path.GetFileName( _inputWavefile ); }
it strips off the path and returns the filename only, FileName.txt.
Even when the filename is not valid, you are still running System.IO.Path.GetFileName() on it.
Assuming this is a PropertyGrid in winforms app. Then it's neither a string concatenation issue, nor PropertyGrid issue, as could be proven by the following snippet. So you need to look elsewhere in your code:
public partial class Form1 : Form {
PropertyGrid pg;
public Form1() {
pg = new PropertyGrid();
pg.Dock = DockStyle.Fill;
this.Controls.Add(pg);
var inputFile = "some fileName.txt";
var obj = new Obj();
obj.One = "Error_" + inputFile;
obj.Two = inputFile + "Error_";
pg.SelectedObject = obj;
}
}
class Obj {
public string One { get; set; }
public string Two { get; set; }
}

How do I check for a URL's top-level domain in ASP.NET/C#?

Let's say "www.mysite.fr/home" is the URL ..Now how do I fetch "fr" out of this ? JUST "fr"
actually what I am trying to do is change masterpages at runtime after detecting a visitor's country..Yes I can use the countryCode variable which is there in some other class but thot may be I can do it like this only..just wanted to try..logic basically is:-
if(its "fr")
{
//apply masterpage 1
}
if(its "in")
{
//apply masterpage 2
}
Is it possible ? What will be the right way anyway ? Making that class that contains CountryCode variable as a utility class and using the variable from there in my new class
OR
fetch this value "fr" or "in" off the URL ?? How do I do this ? Is it possible?
if (Request.Url.Host.ToLower().EndsWith(".fr"))
{
...
}
There is no method to be used directly. Maybe you can write an extension yourself:
public static string GetDomainTypeName(this Uri uri)
{
if (!uri.HostNameType.Equals(UriHostNameType.Dns) || uri.IsLoopback)
return string.Empty; // or throw an exception
return uri.Host.Split('.').Last();
}
And be careful about the word case! WWW.GOOGLE.FR may make your code incorrect.
I think this should be possible. You can use regex to get the code (fr, in etc.) and change the master page but you'll have to do this before the page_load. By the time asp.net reaches page_load the master page is already set (if I remember correctly). You'll need to handle the PreInit event and set the master page you want to set. So basically do all the regex and master page changing in the PreInit event and you're good to go :)
Here's a description of PreInit (Source: http://msdn.microsoft.com/en-us/library/ms178472.aspx):
PreInit
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
•Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
•Create or re-create dynamic controls.
•Set a master page dynamically.
•Set the Theme property dynamically.
•Read or set profile property values.
For the Current Scenario you can try with the following snippet:
string url = "www.mysite.fr/home";
int nStrLength = url.Length;
int nDot = url.LastIndexOf(".")+1;
int nRestStringLngth = nStrLength - nDot;
string baseDomain = url.Substring(nDot, nRestStringLngth);
int nSlash = baseDomain.IndexOf("/");
baseDomain = baseDomain.Substring(0, nSlash);
Console.WriteLine(baseDomain);
In france it work with EndsWith .fr but in England you have .co.uk or in austria you have .co.at and also .at
You can use the following nuget package. (Install-Package Nager.PublicSuffix)
https://www.nuget.org/packages/Nager.PublicSuffix/
Example:
var domainParser = new DomainParser();
var data = await domainParser.LoadDataAsync();
var tldRules = domainParser.ParseRules(data);
domainParser.AddRules(tldRules);
var domainName = domainParser.Get("sub.test.co.uk");
//domainName.Domain = "test";
//domainName.Hostname = "sub.test.co.uk";
//domainName.RegistrableDomain = "test.co.uk";
//domainName.SubDomain = "sub";
//domainName.TLD = "co.uk";

Categories

Resources