Search Results

Search found 1130 results on 46 pages for 'encode'.

Page 9/46 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Built in method to encode ampersands in urls returned from Url.Action?

    - by Blegger
    I am using Url.Action to generate a URL with two query parameters on a site that has a doctype of XHTML strict. Url.Action("ActionName", "ControllerName", new { paramA="1" paramB="2" }) generates: /ControllerName/ActionName/?paramA=1&paramB=2 but I need it to generate the url with the ampersand escaped: /ControllerName/ActionName/?paramA=1&amp;paramB=2 The fact that Url.Action is returning the URL with the ampersand not escaped breaks my HTML validation. My current solution is to just manually replace ampersand in the URL returned from Url.Action with an escaped ampersand. Is there a built in or better solution to this problem?

    Read the article

  • Javascript to encode cookie contents into a get or post?

    - by beeky
    I want to pass cookie contents from one domain to another. I don't want to get involved with actual cross-domain cookies. I was thinking of reading the cookie on the domain that sets it and then sending it as an encrypted JSON object to the domain that wants to use it. Is there an accepted way of doing this and/or a toolkit that handles this sort of thing? Thanks for any help or advice, -=b

    Read the article

  • How can I encode four unsigned bytes (0-255) to a float and back again using HLSL?

    - by Statement
    Hello! I am facing a task where one of my hlsl shaders require multiple texture lookups per pixel. My 2d textures are fixed to 256*256, so two bytes should be sufficient to address any given texel given this constraint. My idea is then to put two xy-coordinates in each float, giving me eight xy-coordinates in pixel space when packed in a Vector4 format image. These eight coordinates are then used to sample another texture(s). The reason for doing this is to save graphics memory and an attempt to optimize processing time, since then I don't require multiple texture lookups. By the way: Does anyone know if encoding/decoding 16 bytes from/to 4 floats using 1 sampling is slower than 4 samplings with unencoded data?

    Read the article

  • How to force javax xslt transformer to encode entities in utf-8?

    - by calavera.info
    I'm working on filter that should transform an output with some stylesheet. Important sections of code looks like this: PrintWriter out = response.getWriter(); ... StringReader sr = new StringReader(content); Source xmlSource = new StreamSource(sr, requestSystemId); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setParameter("encoding", "UTF-8"); //same result when using ByteArrayOutputStream xo = new java.io.ByteArrayOutputStream(); StringWriter xo = new StringWriter(); StreamResult result = new StreamResult(xo); transformer.transform(xmlSource, result); out.write(xo.toString()); The problem is that national characters are encoded as html entities and not by using UTF. Is there any way to force transformer to use UTF-8 instead of entities?

    Read the article

  • How can I tell groovy/grails not to try to "re-encode" binary data? (Revised title)

    - by ?????
    I have a groovy/grails application that needs to serve images It works fine on my dev box, the image is returned properly. Here's the start of the returned JPEG, as seen by od -cx 0000000 377 330 377 340 \0 020 J F I F \0 001 001 001 001 , d8ff e0ff 1000 464a 4649 0100 0101 2c01 but on the production box, there's some garbage in front, and the d8ff e0ff before the 1000 is missing 0000000 ? ** ** ? ** ** ? ** ** ? ** ** \0 020 J F bfef efbd bdbf bfef efbd bdbf 1000 464a 0000020 I F \0 001 001 001 \0 H \0 H \0 \0 ? ** ** ? 4649 0100 0101 4800 4800 0000 bfef efbd It's the exact same code. I just moved the .war over and run it on a different machine. (Isn't Java supposed to be write once, run everywhere?) Any ideas? An "encoding" problem? The code is sent to the response like this: response.contentType = "image/jpeg"; response.outputStream << out; Here's the code that locates the image on an internal application server and re-serves the image. I've pared down the code a bit to remove the error handling, etc, to make it easier to read. def show = { def address = "http://internal.application.server:9899/img?photoid=${params.id}" def out = new ByteArrayOutputStream() out << new URL(address).openStream() response.contentLength = out.size(); // XXX If you don't do this hack, "head" requests won't work! if (request.method == 'HEAD') { render( text : "", contentType : "image/jpeg" ); } else { response.contentType = "image/jpeg"; response.outputStream << out; } } Update: I tried setting the CharacterEncoding response.setCharacterEncoding("ISO-8859-1"); if (request.method == 'HEAD') { render( text : "", contentType : "image/jpeg" ); } else { response.contentType = "image/jpeg;charset=ISO-8859-1"; response.outputStream << out; } but it made no difference in the output. On my production machine, the binary bytes in the image are re-encoded/escaped as if they were UTF-8 (see Michael's explanation below). It works fine on my development machine.

    Read the article

  • Is there a standard way to encode a .NET string into javascript string for use in MS AJAX?

    - by Rich Andrews
    I'm trying to pass the output of a SQL Server exception to the client using the RegisterStartUpScript method of the MS ScriptManager. This works fine for some errors but when the exception contains single quotes the alert fails. I dont want to only escape single quotes though - Is there a standard function i can call to escape any special chars for use in Javascript? string scriptstring = "alert('" + ex.Message + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", scriptstring , true); Thanks tpeczek, the code almost worked for me :) but with a slight amendment (the escaping of single quotes) it works a treat. I've included my amended version here... public class JSEncode { /// <summary> /// Encodes a string to be represented as a string literal. The format /// is essentially a JSON string. /// /// The string returned includes outer quotes /// Example Output: "Hello \"Rick\"!\r\nRock on" /// </summary> /// <param name="s"></param> /// <returns></returns> public static string EncodeJsString(string s) { StringBuilder sb = new StringBuilder(); sb.Append("\""); foreach (char c in s) { switch (c) { case '\'': sb.Append("\\\'"); break; case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; default: int i = (int)c; if (i < 32 || i > 127) { sb.AppendFormat("\\u{0:X04}", i); } else { sb.Append(c); } break; } } sb.Append("\""); return sb.ToString(); } } As mentioned below - original source: here

    Read the article

  • How do I encode Unicode strings using pyodbc to save to a SAS dataset?

    - by Chris B.
    I'm using Python to read and write SAS datasets, using pyodbc and the SAS ODBC drivers. I can load the data perfectly well, but when I save the data, using something like: cursor.execute('insert into dataset.test VALUES (?)', u'testing') ... I get a pyodbc.Error: ('HY004', '[HY004] [Microsoft][ODBC Driver Manager] SQL data type out of range (0) (SQLBindParameter)') error. The problem seems to be the fact I'm passing a unicode string; what do I need to do to handle this?

    Read the article

  • Why do browsers encode special characters differently with ajax requests?

    - by Andrei Oniga
    I have a web application that reads the values of a few input fields (alphanumeric) and constructs a very simple xml that is passes to the server, using jQuery's $.ajax() method. The template for that xml is: <request> <session>[some-string]</session> <space>[some-string]</space> <plot>[some-string]</plot> ... </request> Sending such requests to the server when the inputs contain Finnish diacritical characters (such as ä or ö) raises a problem in terms of character encoding with different browsers. For instance, if I add the word Käyttötarkoitus" in one of the inputs, here's how Chrome and Firefox send EXACTLY the same request to the server: Chrome: <request> <session>{string-hidden}</session> <space>2080874</space> <plot>Käyttötarkoitus</plot> ... </request> FF 12.0: <request> <session>{string-hidden}</session> <space>2080874</space> <plot>Käyttötarkoitus</plot> ... </request> And here is the code fragment that I use to send the requests: $.ajax({ type: "POST", url: url, dataType: 'xml;charset=UTF-8', data: xml, success: function(xml) { // }, error: function(jqXHR, textStatus, errorThrown) { // } }); Why do I get different encodings and how do I get rid of this difference? I need to fix this problem because it's causing other on the server-side.

    Read the article

  • Which is the best way to encode batch videos on server side?

    - by albanx
    Hello I am making a general question since I am a developer and I have no advance experience on video elaboration. I have to preparare a web application with the purpose to allow video files upload on our company server and then video elaboration by server, on user command. The purpose of the web application is to allow to the user to make some elaboration on video depending on user action launch from the web app: (server has to ) convert video in different format(mp4, flv...) extact keyframes from video and saves them in jpeg format possibility to extract audio from video automatic control of quality audio & video (black frames,silences detection) change scene detection and keyframe extraction ..... This what's my bosses wanted from the web based application (with the server support obviously), and I understand only the first 3 points of this list, the rest for me was arabic.... My question is: Which is the best and fastest server side application for this works, that can support multiple batch video conversions, from command line (comand line for php-soap-socket interaction or something else..)? Is suitable Adobe Media Server for batch video conversion? Which are adobe products that can be used for this purpose? Note: I have experience with Indesign Server scripting programing (sending xml with php and soap call...), and I am looking to something similiar for video elaboration. I will appreciate any answers. THANKS ALL

    Read the article

  • Non-Latin characters in URLs - is it better to encode them or replace with their Latin "counterparts

    - by Pawel Krakowiak
    We're implementing a blog for a site which supports six different languages and five of them have non-Latin characters in their alphabets. We are not sure whether we should have them encoded (that is what we're doing at the moment) Létání s potravinami: Co je dovoleno? becomes l%c3%a9t%c3%a1n%c3%ad-s-potravinami-co-je-dovoleno and the browser displays it as létání-s-potravinami-co-je-dovoleno. or if we should replace them with their Latin "counterparts" (similar looking letters) Létání s potravinami: Co je dovoleno? becomes letani-s-potravinami-co-je-dovoleno. I can't find a definitive answer as to what's better from SEO perspective? Search engine optimization is very important for us. Which approach would you suggest?

    Read the article

  • How do you encode an apostrophe so that it's searchable in mysql?

    - by Yegor
    I don't think that was the most clear question, but an example should make it a little clearer. I have a table filled with movie names, some of which contain apostrophes. I have a search box which is used to find movies. If I perform searches via mov_title = '$search_keywords' it all works, but this method will not yield any results for partial searches, so I have to use this mov_title LIKE '%$search_keywords%' This method works fine for titles that are A-Za-z0-9, but if a title has an apostrophe, it's not able to find the movie, even if I do an exact match. Before the titles are stored in the DB, I put them through this: $search_keywords = htmlspecialchars(mysql_escape_string($_GET["search_keywords"])); So in the DB, there is a forward slash before every single apostrophe. The only way to match a movie title with an apostrophe is to physically put a forward slash in front of the apostrophe, in the search box. This seems so trivial, and I'm sure the solution is painfully obvious, but I'm just not seeing it.

    Read the article

  • How to encode content to send them via jquery to a php file?

    - by phpheini
    I am trying to send a form to a php file via jquery. The problem is, that the content, which has to be sent to the php file, contains slashes (/) since there is bb code inside. So I tried the following: $.ajax( { type: "POST", url: "create.php", data: "content=" + encodeURIComponent(content), cache: false, success: function(message) { $("#somediv").html(message); } }); In the php file I use rawurldecode to decode the content and get my bb codes back which I can then transform into html. The problem is as soon as I put the encodeURIComponent() it will ouput: [object HTMLTextAreaElement] What does that mean, where is my mistake? Thanks for your help! phpheini

    Read the article

  • The model item passed into the dictionary is of type 'System.Collections.Generic.Lis

    - by mazhar
    Calling Index view is giving me this very very annoying error . Can anybody tell me what to do about it Error: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[MvcApplication13.Models.Groups]', but this dictionary requires a model item of type 'MvcApplication13.Helpers.PaginatedList1[MvcApplication13.Models.Groups]'. public ActionResult Index(int? page) { const int pageSize = 10; var group =from p in _db.Groups orderby p.int_GroupId select p; var paginatedGroup = group.Skip((page ?? 0) * pageSize).Take(pageSize).ToList(); return View(paginatedGroup); } View: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" % Index <h2>Index</h2> <table> <tr> <th></th> <th> int_GroupId </th> <th> vcr_GroupName </th> <th> txt_GroupDescription </th> <th> bit_Is_Deletable </th> <th> bit_Active </th> <th> int_CreatedBy </th> <th> dtm_CreatedDate </th> <th> int_ModifiedBy </th> <th> dtm_ModifiedDate </th> </tr> <% foreach (var item in Model) { %> <tr> <td> <%= Html.ActionLink("Edit", "Edit", new { id=item.int_GroupId }) %> | <%= Html.ActionLink("Details", "Details", new { id=item.int_GroupId })%> | <%= Html.ActionLink("Delete", "Delete", new { id=item.int_GroupId })%> </td> <td> <%= Html.Encode(item.int_GroupId) %> </td> <td> <%= Html.Encode(item.vcr_GroupName) %> </td> <td> <%= Html.Encode(item.txt_GroupDescription) %> </td> <td> <%= Html.Encode(item.bit_Is_Deletable) %> </td> <td> <%= Html.Encode(item.bit_Active) %> </td> <td> <%= Html.Encode(item.int_CreatedBy) %> </td> <td> <%= Html.Encode(String.Format("{0:g}", item.dtm_CreatedDate)) %> </td> <td> <%= Html.Encode(item.int_ModifiedBy) %> </td> <td> <%= Html.Encode(String.Format("{0:g}", item.dtm_ModifiedDate)) %> </td> </tr> <% } %> </table> <% if (Model.HasPreviousPage) { % <%= Html.RouteLink("<<<", "UpcomingDinners", new { page = (Model.PageIndex-1) }) % <% } % <% if (Model.HasNextPage) { % <%= Html.RouteLink("", "UpcomingDinners", new { page = (Model.PageIndex + 1) }) % <% } % <p> <%= Html.ActionLink("Create New", "Create") %> </p>

    Read the article

  • Automatically CONCATENATE text on data entry

    - by Bill T
    I am a newbie and need help. I have a table called "Employees". It has 2 fields [number] and [encode]. I want to automatically take whatever number is entered into [number] and store it in [encode] so that it is preceded by the appropriate amount of 0's to always make 12 digits. Example: user enters '123' into [number], '000000000123' is automatically stored in [encode] user enters '123456789' into [number], '000123456789' is automatically stored in [encode] I think i want to write a trigger to accomplish this. I think that would make it happen at the time of data entry. is that right? The main idea is would be something like this: variable1 = LENGTH [number] variable2 = REPEAT (0,12-variable1) variable3 = CONCATENATE (variable2, [number]) [encode] = variable3 I just don't know enough to make this happen ANY help would be FANTASTIC. I have SQL-SERVER 2005 and both fields are text

    Read the article

  • Java to C# code converter

    - by acadia
    Hello, Are there any converters available that converts Java code to C#? I need to convert the below code into C# String token = new String(""); URL url1 =new URL( "http", domain, Integer.valueOf(portnum), "/Workplace/setCredentials?op=getUserToken&userId="+username+"&password="+password +"&verify=true"); URLConnection conn1=url1.openConnection(); ((HttpURLConnection)conn1).setRequestMethod("POST"); InputStream contentFileUrlStream = conn1.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(contentFileUrlStream)); token=br.readLine(); String encodedAPIToken = URLEncoder.encode(token); String doubleEncodedAPIToken ="ut=" + encodedAPIToken;//.substring(0, encodedAPIToken.length()-1); //String doubleEncodedAPIToken ="ut=" + URLEncoder.encode(encodedAPIToken); //String userToken = "ut=" + URLEncoder.encode(token, "UTF-8"); //URLEncoder.encode(token); String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8"); url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken; String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8"); url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken; Thanks in advance

    Read the article

  • Sending an HTTP POST request through the android emulator doesn't work

    - by Sotirios Delimanolis
    I'm running a tomcat servlet on my local machine and an Android emulator with an app that makes a post request to the servlet. The code for the POST is below (without exceptions and the like): String strUrl = "http://10.0.2.2:8080/DeviceDiscoveryServer/server/devices/"; Device device = Device.getUniqueInstance(); urlParameters += URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(device.getUser(), "UTF-8"); urlParameters += "&" + URLEncoder.encode("port", "UTF-8") + "=" + URLEncoder.encode(new Integer(Device.PORT).toString(), "UTF-8"); urlParameters += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(device.getAddress().getHostAddress(), "UTF-8"); URL url = new URL(strUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(urlParameters); wr.flush(); wr.close(); Whenever this code is executed, the servlet isn't called. However if I change the type of the request to 'GET' and don't write anything to the outputstream, the servlet gets called and everything works fine. Am I just not making the POST correctly or is there some other error?

    Read the article

  • Visually and audibly unambiguous subset of the Latin alphabet?

    - by elliot42
    Imagine you give someone a card with the code "5SBDO0" on it. In some fonts, the letter "S" is difficult to visually distinguish from the number five, (as with number zero and letter "O"). Reading the code out loud, it might be difficult to distinguish "B" from "D", necessitating saying "B as in boy," "D as in dog," or using a "phonetic alphabet" instead. What's the biggest subset of letters and numbers that will, in most cases, both look unambiguous visually and sound unambiguous when read aloud? Background: We want to generate a short string that can encode as many values as possible while still being easy to communicate. Imagine you have a 6-character string, "123456". In base 10 this can encode 10^6 values. In hex "1B23DF" you can encode 16^6 values in the same number of characters, but this can sound ambiguous when read aloud. ("B" vs. "D") Likewise for any string of N characters, you get (size of alphabet)^N values. The string is limited to a length of about six characters, due to wanting to fit easily within the capacity of human working memory capacity. Thus to find the max number of values we can encode, we need to find that largest unambiguous set of letters/numbers. There's no reason we can't consider the letters G-Z, and some common punctuation, but I don't want to have to go manually pairwise compare "does G sound like A?", "does G sound like B?", "does G sound like C" myself. As we know this would be O(n^2) linguistic work to do =)...

    Read the article

  • Android: HttpURLConnection not working properly

    - by giorgiline
    I'm trying to get the cookies from a website after sending user credentials through a POST Request an it seems that it doesn't work in android this way. ¿Am I doing something bad?. Please help. I've searched here in different posts but there's no useful answer. It's curious that this run in a desktop Java implementation it works perfect but it crashes in Android platform. And it is exactly the same code, specifically when calling HttpURLConnection.getHeaderFields(), it also happens with other member methods. It's a simple code and I don't know why the hell isn't working. DESKTOP CODE: This goes just in the main() HttpURLConnection connection = null; OutputStream out = null; try { URL url = new URL("http://www.XXXXXXXX.php"); String charset = "UTF-8"; String postback = "1"; String user = "XXXXXXXXX"; String password = "XXXXXXXX"; String rememberme = "on"; String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s" , URLEncoder.encode(postback, charset) , URLEncoder.encode(user,charset) , URLEncoder.encode(password, charset) , URLEncoder.encode(rememberme, charset)); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", charset); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(query.length()); out = connection.getOutputStream (); out.write(query.getBytes(charset)); if (connection.getHeaderFields() == null){ System.out.println("Header null"); }else{ for (String cookie: connection.getHeaderFields().get("Set-Cookie")){ System.out.println(cookie.split(";", 2)[0]); } } } catch (IOException e){ e.printStackTrace(); } finally { try { out.close();} catch (IOException e) { e.printStackTrace();} connection.disconnect(); } So the output is: login_key=20ad8177db4eca3f057c14a64bafc2c9 FASID=cabf20cc471fcacacdc7dc7e83768880 track=30c8183e4ebbe8b3a57b583166326c77 client-data=%7B%22ism%22%3Afalse%2C%22showm%22%3Afalse%2C%22ts%22%3A1349189669%7D ANDROID CODE: This goes inside doInBackground AsyncTask body HttpURLConnection connection = null; OutputStream out = null; try { URL url = new URL("http://www.XXXXXXXXXXXXXX.php"); String charset = "UTF-8"; String postback = "1"; String user = "XXXXXXXXX"; String password = "XXXXXXXX"; String rememberme = "on"; String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s" , URLEncoder.encode(postback, charset) , URLEncoder.encode(user,charset) , URLEncoder.encode(password, charset) , URLEncoder.encode(rememberme, charset)); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", charset); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(query.length()); out = connection.getOutputStream (); out.write(query.getBytes(charset)); if (connection.getHeaderFields() == null){ Log.v(TAG, "Header null"); }else{ for (String cookie: connection.getHeaderFields().get("Set-Cookie")){ Log.v(TAG, cookie.split(";", 2)[0]); } } } catch (IOException e){ e.printStackTrace(); } finally { try { out.close();} catch (IOException e) { e.printStackTrace();} connection.disconnect(); } And here there is no output, it seems that connection.getHeaderFields() doesn't return result. It takes al least 30 seconds to show the Log: 10-02 16:56:25.918: V/class com.giorgi.myproject.activities.HomeActivity(2596): Header null

    Read the article

  • New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)

    - by ScottGu
    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu] This is the nineteenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. Today’s post covers a small, but very useful, new syntax feature being introduced with ASP.NET 4 – which is the ability to automatically HTML encode output within code nuggets.  This helps protect your applications and sites against cross-site script injection (XSS) and HTML injection attacks, and enables you to do so using a nice concise syntax. HTML Encoding Cross-site script injection (XSS) and HTML encoding attacks are two of the most common security issues that plague web-sites and applications.  They occur when hackers find a way to inject client-side script or HTML markup into web-pages that are then viewed by other visitors to a site.  This can be used to both vandalize a site, as well as enable hackers to run client-script code that steals cookie data and/or exploits a user’s identity on a site to do bad things. One way to help mitigate against cross-site scripting attacks is to make sure that rendered output is HTML encoded within a page.  This helps ensures that any content that might have been input/modified by an end-user cannot be output back onto a page containing tags like <script> or <img> elements.  ASP.NET applications (especially those using ASP.NET MVC) often rely on using <%= %> code-nugget expressions to render output.  Developers today often use the Server.HtmlEncode() or HttpUtility.Encode() helper methods within these expressions to HTML encode the output before it is rendered.  This can be done using code like below: While this works fine, there are two downsides of it: It is a little verbose Developers often forget to call the HtmlEncode method New <%: %> Code Nugget Syntax With ASP.NET 4 we are introducing a new code expression syntax (<%:  %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so.  This eliminates the need to explicitly HTML encode content like we did in the example above.  Instead you can just write the more concise code below to accomplish the same thing: We chose the <%: %> syntax so that it would be easy to quickly replace existing instances of <%= %> code blocks.  It also enables you to easily search your code-base for <%= %> elements to find and verify any cases where you are not using HTML encoding within your application to ensure that you have the correct behavior. Avoiding Double Encoding While HTML encoding content is often a good best practice, there are times when the content you are outputting is meant to be HTML or is already encoded – in which case you don’t want to HTML encode it again.  ASP.NET 4 introduces a new IHtmlString interface (along with a concrete implementation: HtmlString) that you can implement on types to indicate that its value is already properly encoded (or otherwise examined) for displaying as HTML, and that therefore the value should not be HTML-encoded again.  The <%: %> code-nugget syntax checks for the presence of the IHtmlString interface and will not HTML encode the output of the code expression if its value implements this interface.  This allows developers to avoid having to decide on a per-case basis whether to use <%= %> or <%: %> code-nuggets.  Instead you can always use <%: %> code nuggets, and then have any properties or data-types that are already HTML encoded implement the IHtmlString interface. Using ASP.NET MVC HTML Helper Methods with <%: %> For a practical example of where this HTML encoding escape mechanism is useful, consider scenarios where you use HTML helper methods with ASP.NET MVC.  These helper methods typically return HTML.  For example: the Html.TextBox() helper method returns markup like <input type=”text”/>.  With ASP.NET MVC 2 these helper methods now by default return HtmlString types – which indicates that the returned string content is safe for rendering and should not be encoded by <%: %> nuggets.  This allows you to use these methods within both <%= %> code nugget blocks: As well as within <%: %> code nugget blocks: In both cases above the HTML content returned from the helper method will be rendered to the client as HTML – and the <%: %> code nugget will avoid double-encoding it. This enables you to default to always using <%: %> code nuggets instead of <%= %> code blocks within your applications.  If you want to be really hardcore you can even create a build rule that searches your application looking for <%= %> usages and flags any cases it finds as an error to enforce that HTML encoding always takes place. Scaffolding ASP.NET MVC 2 Views When you use VS 2010 (or the free Visual Web Developer 2010 Express) you’ll find that the views that are scaffolded using the “Add View” dialog now by default always use <%: %> blocks when outputting any content.  For example, below I’ve scaffolded a simple “Edit” view for an article object.  Note the three usages of <%: %> code nuggets for the label, textbox, and validation message (all output with HTML helper methods): Summary The new <%: %> syntax provides a concise way to automatically HTML encode content and then render it as output.  It allows you to make your code a little less verbose, and to easily check/verify that you are always HTML encoding content throughout your site.  This can help protect your applications against cross-site script injection (XSS) and HTML injection attacks.  Hope this helps, Scott

    Read the article

  • Creating Rich View Components in ASP.NET MVC

    - by kazimanzurrashid
    One of the nice thing of our Telerik Extensions for ASP.NET MVC is, it gives you an excellent extensible platform to create rich view components. In this post, I will show you a tiny but very powerful ListView Component. Those who are familiar with the Webforms ListView component already knows that it has the support to define different parts of the component, we will have the same kind of support in our view component. Before showing you the markup, let me show you the screenshots first, lets say you want to show the customers of Northwind database as a pagable business card style (Yes the example is inspired from our RadControls Suite) And here is the markup of the above view component. <h2>Customers</h2> <% Html.Telerik() .ListView(Model) .Name("customers") .PrefixUrlParameters(false) .BeginLayout(pager => {%> <table border="0" cellpadding="3" cellspacing="1"> <tfoot> <tr> <td colspan="3" class="t-footer"> <% pager.Render(); %> </td> </tr> </tfoot> <tbody> <tr> <%}) .BeginGroup(() => {%> <td> <%}) .Item(item => {%> <fieldset style="border:1px solid #e0e0e0"> <legend><strong>Company Name</strong>:<%= Html.Encode(item.DataItem.CompanyName) %></legend> <div> <div style="float:left;width:120px"> <img alt="<%= item.DataItem.CustomerID %>" src="<%= Url.Content("~/Content/Images/Customers/" + item.DataItem.CustomerID + ".jpg") %>"/> </div> <div style="float:right"> <ul style="list-style:none none;padding:10px;margin:0"> <li> <strong>Contact Name:</strong> <%= Html.Encode(item.DataItem.ContactName) %> </li> <li> <strong>Title:</strong> <%= Html.Encode(item.DataItem.ContactTitle) %> </li> <li> <strong>City:</strong> <%= Html.Encode(item.DataItem.City)%> </li> <li> <strong>Country:</strong> <%= Html.Encode(item.DataItem.Country)%> </li> <li> <strong>Phone:</strong> <%= Html.Encode(item.DataItem.Phone)%> </li> <li> <div style="float:right"> <%= Html.ActionLink("Edit", "Edit", new { id = item.DataItem.CustomerID }) %> <%= Html.ActionLink("Delete", "Delete", new { id = item.DataItem.CustomerID })%> </div> </li> </ul> </div> </div> </fieldset> <%}) .EmptyItem(() =>{%> <fieldset style="border:1px solid #e0e0e0"> <legend>Empty</legend> </fieldset> <%}) .EndGroup(() => {%> </td> <%}) .EndLayout(pager => {%> </tr> </tbody> </table> <%}) .GroupItemCount(3) .PageSize(6) .Pager<NumericPager>(pager => pager.ShowFirstLast()) .Render(); %> As you can see that you have the complete control on the final angel brackets and like the webform’s version you also can define the templates. You can also use this component to show Master/Detail data, for example the customers and its order like the following: I am attaching the complete source code along with the above examples for your review, what do you think, how about creating some component with our extensions? Download: MvcListView.zip

    Read the article

  • Javascript and PHP how should I en/decode my data

    - by Ron
    Hello everyone. I whould like to know in what encryption should I encode my data and why first of all, I use GET method because it is search engine inside website. second, I use RTL language (hebrew) and thrid which basically is why I ask this question - firefox and safari (as I understood) encode and decode urls automaticly so if I encoded url, in firefox I will see it decoded which is good but if I copy-paste the url to the address bar and than enter the site firefox encode the uncoded url to utf (i think). anyway, what en/decode should I use, and how can I overcome the firefox auto en/decode?

    Read the article

  • The parameters dictionary contains a null entry for parameter

    - by ognjenb
    <%using (Html.BeginForm("OrderDevice", "ImportXML", FormMethod.Post)) { %> <table id="OrderDevices" class="data-table"> <tr> <th> DeviceId </th> <th> Id </th> <th> OrderId </th> </tr> <% foreach (var item in Model) { %> <tr> <td> <input readonly="readonly" class="" id="DeviceId" type="text" name="<%= Html.Encode(item.DeviceId) %>" value="<%= Html.Encode(item.DeviceId) %>" style="width: 61px" /> </td> <td> <input readonly="readonly" class="" id="c" type="text" name= "<%= Html.Encode(item.Id) %>" value=" <%= Html.Encode(item.Id) %>" style="width: 50px" /> </td> <td> <input readonly="readonly" class="" id="OrderId" type="text" name= " <%= Html.Encode(item.OrderId) %>" value="<%= Html.Encode(item.OrderId) %> " style="width: 49px" /> </td> </tr> <% } %> </table> <input type="submit" value="Create"/> <%} %> My controller action: [AcceptVerbs(HttpVerbs.Post)] public ActionResult OrderDevice(int id) { try { // TODO: Add insert logic here orderdevice ord = new orderdevice(); ord.Id = System.Convert.ToInt32(Request.Form["Id"]); ord.OrderId = System.Convert.ToInt32(Request.Form["OrderId"]); ord.DeviceId = System.Convert.ToInt32(Request.Form["DeviceId"]); XMLEntities.AddToorderdevice(ord); XMLEntities.SaveChanges(); return RedirectToAction("Index"); } catch { return View("Index"); } } When post a form I have this error: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult OrderDevice(Int32)' in 'MvcKVteam.Controllers.ImportXMLController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters How fix it?

    Read the article

  • Many to Many Logic in ASP.NET MVC

    - by Jonathan Stowell
    Hi All, I will restrict this to the three tables I am trying to work with Problem, Communications, and ProbComms. The scenario is that a Student may have many Problems concurrently which may affect their studies. Lecturers may have future communications with a student after an initial problem is logged, however as a Student may have multiple Problems the Lecturer may decide that the discussion they had is related to more than one Problem. Here is a screenshot of the LINQ representation of my DB: LINQ Screenshot At the moment in my StudentController I have a StudentFormViewModel Class: // //ViewModel Class public class StudentFormViewModel { IProbCommRepository probCommRepository; // Properties public Student Student { get; private set; } public IEnumerable<ProbComm> ProbComm { get; private set; } // // Dependency Injection enabled constructors public StudentFormViewModel(Student student, IEnumerable<ProbComm> probComm) : this(new ProbCommRepository()) { this.Student = student; this.ProbComm = probComm; } public StudentFormViewModel(IProbCommRepository pRepository) { probCommRepository = pRepository; } } When I go to the Students Detail Page this runs: public ActionResult Details(string id) { StudentFormViewModel viewdata = new StudentFormViewModel(studentRepository.GetStudent(id), probCommRepository.FindAllProblemComms(id)); if (viewdata == null) return View("NotFound"); else return View(viewdata); } The GetStudent works fine and returns an instance of the student to output on the page, below the student I output all problems logged against them, but underneath these problems I want to show the communications related to the Problem. The LINQ I am using for ProbComms is This is located in the Model class ProbCommRepository, and accessed via a IProbCommRepository interface: public IQueryable<ProbComm> FindAllProblemComms(string studentEmail) { return (from p in db.ProbComms where p.Problem.StudentEmail.Equals(studentEmail) orderby p.Problem.ProblemDateTime select p); } However for example if I have this data in the ProbComms table: ProblemID CommunicationID 1 1 1 2 The query returns two rows so I assume I somehow have to groupby Problem or ProblemID but I am not too sure how to do this with the way I have built things as the return type has to be ProbComm for the query as thats what Model class its located in. When it comes to the view the Details.aspx calls two partial views each passing the relevant view data through, StudentDetails works fine page: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MitigatingCircumstances.Controllers.StudentFormViewModel>" %> <% Html.RenderPartial("StudentDetails", this.ViewData.Model.Student); %> <% Html.RenderPartial("StudentProblems", this.ViewData.Model.ProbComm); %> StudentProblems uses a foreach loop to loop through records in the Model and I am trying another foreach loop to output the communication details: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MitigatingCircumstances.Models.ProbComm>>" %> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("DIV.ContainerPanel > DIV.collapsePanelHeader > DIV.ArrowExpand").toggle( function() { $(this).parent().next("div.Content").show("slow"); $(this).attr("class", "ArrowClose"); }, function() { $(this).parent().next("div.Content").hide("slow"); $(this).attr("class", "ArrowExpand"); }); }); </script> <div class="studentProblems"> <% var i = 0; foreach (var item in Model) { %> <div id="ContainerPanel<%= i = i + 1 %>" class="ContainerPanel"> <div id="header<%= i = i + 1 %>" class="collapsePanelHeader"> <div id="dvHeaderText<%= i = i + 1 %>" class="HeaderContent"><%= Html.Encode(String.Format("{0:dd/MM/yyyy}", item.Problem.ProblemDateTime))%></div> <div id="dvArrow<%= i = i + 1 %>" class="ArrowExpand"></div> </div> <div id="dvContent<%= i = i + 1 %>" class="Content" style="display: none"> <p> Type: <%= Html.Encode(item.Problem.CommunicationType.TypeName) %> </p> <p> Problem Outline: <%= Html.Encode(item.Problem.ProblemOutline)%> </p> <p> Mitigating Circumstance Form: <%= Html.Encode(item.Problem.MCF)%> </p> <p> Mitigating Circumstance Level: <%= Html.Encode(item.Problem.MitigatingCircumstanceLevel.MCLevel)%> </p> <p> Absent From: <%= Html.Encode(String.Format("{0:g}", item.Problem.AbsentFrom))%> </p> <p> Absent Until: <%= Html.Encode(String.Format("{0:g}", item.Problem.AbsentUntil))%> </p> <p> Requested Follow Up: <%= Html.Encode(String.Format("{0:g}", item.Problem.RequestedFollowUp))%> </p> <p>Problem Communications</p> <% foreach (var comm in Model) { %> <p> <% if (item.Problem.ProblemID == comm.ProblemID) { %> <%= Html.Encode(comm.ProblemCommunication.CommunicationOutline)%> <% } %> </p> <% } %> </div> </div> <br /> <% } %> </div> The issue is that using the example data before the Model has two records for the same problem as there are two communications for that problem, therefore duplicating the output. Any help with this would be gratefully appreciated. Thanks, Jon

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >