Empty first line in razor mvc 4 rc - razor

I've migrated from mvc 3 to mvc 4 and encountered with the following problem.
#using InvoiceDocflow.Controllers
#{
Response.ContentType = "text/xml";
}
<?xml version="1.1" encoding="UTF-8" ?>
<dc>
#foreach (var dcLink in (IEnumerable<DcLink>)ViewData["SupportedDcs"])
{
<link rel="#dcLink.RelUri.ToString()" href="#dcLink.DcUri.ToString()" />
}
</dc>
This is my view. My layout is just one line
#RenderBody()
So in mvc 3 <?xml version="1.1" encoding="UTF-8" ?> appeared in the first line, but now, its appears on the second line, leaving th first line empty.
Can I make it render on the first line as it was in mvc 3?
By the way.
#using InvoiceDocflow.Controllers
#{
Response.ContentType = "text/xml";
}<?xml version="1.1" encoding="UTF-8" ?>
This would work, but this is not what I whant to do at all.

I ran into a similar problem with blank lines at the top of the page when trying to return a cache manifest file. Solution, Add a Response.Write("..."), this will be at the first line of the page.
#{
Layout = null;
Response.Write("CACHE MANIFEST");
} .......

Temporary fix? ActionFilter and strip out the empty first line? Clearly you could also do other minification on the response if suitable.
public class TranslationFilter : MemoryStream
{
private Stream filter = null;
public TranslationFilter(HttpResponseBase httpResponseBase)
{
filter = httpResponseBase.Filter;
}
public override void Write(byte[] buffer, int offset, int count)
{
var response = UTF8Encoding.UTF8.GetString(buffer);
// remove all newlines
response = response.Replace(System.Environment.NewLine, "");
/* remove just first empty line
if (response.Substring(0, 2) == "\r\n")
{
response = response.Substring(2, response.Length - 2);
} */
filter.Write(UTF8Encoding.UTF8.GetBytes(response), offset, UTF8Encoding.UTF8.GetByteCount(response));
}
}
public class ResponseFilter : ActionFilterAttribute
{
public ResponseFilter()
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
filterContext.HttpContext.Response.Filter = new TranslationFilter(filterContext.HttpContext.Response);
}
}
And add it onto the Controller method?
[ResponseFilter]
public ActionResult Index()
{
return View();
}

I know this is an old question but I found it when I was searching for a solution to this problem.
Since no one has an easy solution, here is mine:
I was able to fix this by using a partial view instead of a normal view.
I believe the problem comes down to the layout, even if you set it to null it still seems to add a blank first line. The #{} ads a blank line also, so you must move it to the bottom of your view.
So just add a partial view and have your controller return the partial view as such:
public ActionResult GenerateXML()
{
return PartialView("_XML");
}
Then in your partial view you will need to set it up like this (with your #{} at the bottom):
#model string
<?xml version="1.0" encoding="UTF-8" ?>
<response>
<message>#Model</message>
</response>
#{ Response.ContentType = "text/xml";}
This will result in an HTML source of:
<?xml version="1.0" encoding="UTF-8" ?>
<response>
<message>Response Message</message>
</response>
I hope this helps others who run into this problem.

I know you suggested just moving the tag to the end of the #{} but why not place it before that. Moreover, is this blank space causing an error or an issue? You can clearly see that it is because of whitespace created by your code and not from mvc or razor.
Perhaps something like this:
#using InvoiceDocflow.Controllers
<?xml version="1.1" encoding="UTF-8" ?>
#{
Response.ContentType = "text/xml";
}

None of the solutions above worked for me, so after spending a long time trying to fix it - it should be very easy since it's just an empty line - I wrote a blog post about it.
http://devstuffs.wordpress.com/2014/02/07/first-line-empty-in-razor/

I solved the similar problem this way:
_ViewStart.cshtml
#{
Layout = null;
Response.Write("<!DOCTYPE html>");
}
Another .cshtml
#model ViewModel<EshopWebsiteOrder>
<html>
<head>
<meta charset="utf-8" />
Finally, it makes sense define common DOCTYPE on one place.

Another simple fix without the ResponseFilter. Simply put the #using at the bottom of the cshtml file:
<?xml version="1.1" encoding="UTF-8" ?>
<dc>
#foreach (var dcLink in (IEnumerable<DcLink>)ViewData["SupportedDcs"])
{
<link rel="#dcLink.RelUri.ToString()" href="#dcLink.DcUri.ToString()" />
}
</dc>
#using InvoiceDocflow.Controllers
#{
Response.ContentType = "text/xml";
}

If you move:
<?xml version="1.1" encoding="UTF-8" ?>
into the top of a Layout template then have your xml page inherit that and output your xml data it should work.

Related

Exception when using SkiaSharp API in Xamarin Forms Tabbed Page

I'm facing some problems at the time of painting a circle with the SkiaSharp API in one of the children pages of a Tabbed Page in Xamarin Forms.
Although I get no errors during the building of the project, whenever I enter the page in which the circle is supposed to be drawn during the on device debugging, the application throws a "System.InvalidCastException: Specified cast is not valid" message and it crashes.
This is the XAML code of the Tabbed Page:
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:me="clr-namespace:TestBth;assembly=TestBth"
x:Class="TestBth.MyTabbedPage">
<TabbedPage.Children>
<me:ConnectPage />
<me:LissajousPage />
<me:ParametersPage />
</TabbedPage.Children>
<!--Pages can be added as references or inline-->
</TabbedPage>
This is the XAML code of the page that's causing the trouble:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:skia="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
xmlns:local="clr-namespace:TestBth"
x:Class="TestBth.LissajousPage"
Title="Lissajous">
<skia:SKCanvasView x:Name="canvasView"
PaintSurface="canvasView_PaintSurface" />
</ContentPage>
And this is the internal code of the same page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using SkiaSharp;
using SkiaSharp.Views.Forms;
namespace TestBth
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LissajousPage : ContentPage
{
SKPaint blackFillPaint = new SKPaint
{
Style = SKPaintStyle.Fill,
Color = SKColors.Black
};
public LissajousPage()
{
InitializeComponent();
}
private void canvasView_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
SKSurface surface = e.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear(SKColors.CornflowerBlue);
int width = e.Info.Width;
int height = e.Info.Height;
//Set transforms
canvas.Translate(width / 2, height / 2);
canvas.Scale(width / 200f);
//Clock Background
canvas.DrawCircle(0, 0, 100, blackFillPaint);
}
}
}
Any idea about why could this be happening?
Thanks in advance.
For my surprise, it turns out the SkiaSharp.Views.Forms Nuget package was not installed for Android.
I specified that I wanted to install it in all my projects but there must have been a problem during the installation.
I installed the package individually for Android and it works fine now.
Sorry for the inconvenience.

ASP.NET Page ViewData Overwritten (missing)

Contents of _ViewStart.cshtml
#{
Layout = "_Layout";
ViewData["IndexLink"] = Context.Request.Path != "/" ? "/Index" : "";
}
Contents of Downloads.cshtml
#page
#model DownloadsModel
#{
ViewData["Title"] = "Downloads";
}
Snippet from _Layout.cshtml
<title>#ViewData["Title"] - ABC Sofware LLC</title>
Problem:
The <title> tag is being rendered without the view's title.
Troubleshooting Steps:
I put a break point in _Layout.cshtml to see what
ViewData contains. It has one key instead of two.
#ViewData.Keys
Count = 1
[0]: "IndexLink"
If I remove the ViewData["IndexLink"] line from _ViewStart.cshtml then ViewData["Title"] is set.
#ViewData.Keys
Count = 1
[0]: "Title"
Why does setting a ViewData key in _ViewStart.html break ViewData in the views?
Looks like this is currently a bug (see https://github.com/aspnet/Mvc/issues/7675 -- planned to be fixed in Core 2.2.0) but the current workaround is instead of:
ViewData["Key"]
you would use
ViewContext.ViewData["Key"]
in both _ViewStart.cshtml and Downloads.cshtml. Referencing
#ViewData["Key"]
in _Layout.cshtml still seems to work fine for me.

Reading embedded HTML in an XML document with QXmlStreamReader

Using QXmlStreamReader, I would like to have XML files with rich text formatting, using HTML tags. For instance, in this file, it would be nice to have access to <em> and other HTML tags for formatting text. (And with Qt I can put HTML anywhere, in a QLabel or something.)
<?xml version="1.0" encoding="UTF-8"?>
<course name="Introductory Course">
<course-description>Welcome to the <em>basic course</em>.</course-description>
</course>
If I use QXmlStreamReader::readElementText(QXmlStreamReader::IncludeChildElements) when at the start element of <course-description>, I get the text inside <course-description> stripped of the tags, for example Welcome to the basic course.
Of course, I would like to do this without having to account for every single HTML tag in my code.
What I ended up doing is creating a method that I can use in places where I would otherwise call QXmlStreamReader::readElementText. In the XML file, I mark a tag with the XHTML namespace:
<?xml version="1.0" encoding="UTF-8"?>
<course name="Introductory Course">
<course-description xmlns="http://www.w3.org/1999/xhtml">Welcome to the <em>basic course</em>.</course-description>
</course>
Then whenever I read a tag with QXmlStreamReader, I can call readHtml. If the element has the XHTML namespace, it reads and returns all the elements until it reaches the closing element. (This implies that an element with the same name as the namespace-containing element (<course-description> above), cannot be included in the HTML code.)
QString MyClass::readHtml(QXmlStreamReader &xml)
{
if( xml.namespaceUri().toString() != "http://www.w3.org/1999/xhtml" )
{
return xml.readElementText(QXmlStreamReader::IncludeChildElements);
}
QString terminatingElement = xml.name().toString();
QString html;
QXmlStreamWriter writer(&html);
do
{
xml.readNext();
switch( xml.tokenType() )
{
case QXmlStreamReader::StartElement:
writer.writeStartElement(xml.name().toString());
writer.writeAttributes(xml.attributes());
break;
case QXmlStreamReader::EndElement:
writer.writeEndElement();
break;
case QXmlStreamReader::Characters:
writer.writeCharacters(xml.text().toString());
break;
// a more thorough approach would handle these; enumerating them removes a compiler warning
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
}
while (!xml.atEnd() && xml.name() != terminatingElement );
return html;
}

generating page title with razor script - umbraco

So I am trying to create a script whereby depending on the document type of the page a certain pre-defined title tag format will appear, if there is nothing already written in an overwriting custom title input. I have inserted the macro within the title tag on my master template but keep on getting an Error loading Razor Script message .
Html
<title>
<umbraco:Macro Alias="NewPageTitle" runat="server"></umbraco:Macro>
</title>
Script -
#inherits umbraco.MacroEngines.DynamicNodeContext
#using umbraco.MacroEngines
#{
if(String.IsNullOrEmpty(#Model.tabName.ToString()) == false )
{
#Model.tabName
}
else if(#Model.DescendantsOrSelf("Country"))
{
<text>
Holidays in #Model.Name
</text>
}
else
{
#Model.Name;
}
}
Any help would be greatly appreciated.
Try this code out. The problem with your original code is that you were using "#Model.DescendantsOrSelf("Country")" as a boolean, and it is a list. I also removed your comparison for if(String.IsNullOrEmpty(#Model.tabName.ToString())).
Also, if you add ?umbDebugShowTrace=true to the end of your URL, you can get some valuable debugging information. There is a Chrome Extension called "Umbraco Debug" that I use to quickly access that query string and information. You may find it useful.
#inherits umbraco.MacroEngines.DynamicNodeContext
#using umbraco.MacroEngines
#{
if(String.IsNullOrEmpty(#Model.tabName.ToString()))
{
#Model.tabName
}
else if(#Model.DescendantsOrSelf("Country").Count() > 0)
{
<text>
Holidays in #Model.Name
</text>
}
else
{
#Model.Name;
}
}
its very simple just add following code into your title tag
#Umbraco.Field("pageName")
will display pageName,you may also add custom properties from document type.
e.g. you have added new property like "metaKeywords" with value "html,javascript,xml",fetch that values as following way...
#Umbraco.Field("metaKeywords")
even you don't need to add custom properties in your model

How to set codes in html page?

I am new in html and i'm making a html page in which i want to display some code, but it not showing proper way like what we are writing in notepad. So, i have to write each and every line or any other solution is there. Suppose this is the code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.liste);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Setup the list view
final ListView prestListView = (ListView) findViewById(R.id.list);
final prestationAdapterEco prestationAdapterEco = new prestationAdapterEco(this, R.layout.prestation);
prestListView.setAdapter(prestationAdapterEco);
// Populate the list, through the adapter
for(final prestationEco entry : getPrestations()) {
prestationAdapterEco.add(entry);
}
prestListView.setClickable(true);
prestListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = prestListView.getItemAtPosition(position);
String str=(String)o;//As you are using Default String Adapter
Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
}
});
}
and i want to show it on html page like this only. Please help.. Thanks
<pre><code> code... </code></pre>
This seems to be the best method they've found here: <code> vs <pre> vs <samp> for inline and block code snippets
It also happens to be the recommended way to show a sample of computer code on W3.org.
I think you're looking for code/syntax highlighting in HTML pages. Unfortunately there is no highlighting feature using tags in HTML.
In HTML You can use:
<code>You code goes here..</code>
For more reference: http://www.w3schools.com/tags/tag_code.asp and the list of global attributes code tag supports: http://www.w3schools.com/tags/ref_standardattributes.asp
However, you can make use of some javascripts which enables syntaxt highlighting in HTML.
You can check this thread: "Syntax highlighting code with Javascript" for more info.