This is another misleading error, it could either be a typo, cookie instead of cookies or you must reference with an index of some description for example:
Response.Cookies["CookieName"]["Key"]
Netferrets Online Blog, Internet Related Programming Solutions, Created in C# .net, VB .net, MS SQL Server Javascript, HTML and CSS. Proving sample solutions to problems found when creating web application solutions.
Friday, 19 October 2012
Thursday, 18 October 2012
EntityDataSource - SQL Equivilent To Join, Include, Where
I was trying to get my [tbl_users] table related to my news table in order to return the username as opposed to the id.
After lots of messing about, I finally found how to do this with the following method:
DefaultContainerName="NewsEntities1" EnableFlattening="False" EntitySetName="tbl_News"
Include="tbl_Users" Where="it.Category_ID = @CategoryID">
When outputt to a control you will need to use something along the lines of the related data, everything else you can reference as normal with eval:
By <%# Eval("tbl_Users.User_Displayname")%>
To give you more of an idea of the database structure, here is a screenshot:
I will try to elaborate further in the future, but unfortunatley I am extremely busy lately.
Hope this helps as I know it was driving me up the wall at one point.
After lots of messing about, I finally found how to do this with the following method:
Include="tbl_Users" Where="it.Category_ID = @CategoryID">
When outputt to a control you will need to use something along the lines of the related data, everything else you can reference as normal with eval:
By <%# Eval("tbl_Users.User_Displayname")%>
To give you more of an idea of the database structure, here is a screenshot:
I will try to elaborate further in the future, but unfortunatley I am extremely busy lately.
Hope this helps as I know it was driving me up the wall at one point.
Keywords:
.net c#,
Entities,
entitydatasource,
join,
multiple results,
Select,
Where
Entity Framework, Nested Controls, Nested Datasources
Well after lots of searching for a decent example of how to nest entity items using entity framework I ended up with my own solution after many painful hours.
The following code, passes a parameter/value through from a control the nested datasource and then in turn populates the control. This is most useful when creating categories.
This is still work in progress, but hopefully it can be useful for those struggling with this entity framework lark as its not the easiest thing to work with.
<!--Categories-->
<asp:EntityDataSource ID="CategoriesDataSource" runat="server" ConnectionString="name=NewsEntities1"
DefaultContainerName="NewsEntities1" EnableFlattening="False" EntitySetName="tbl_NewsCategories"
Select="it.[Category_ID], it.[Category_Title]">
</asp:EntityDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="CategoriesDataSource">
<ItemTemplate>
<div class="Article">
<asp:Label ID="CategoryHeading" runat="server"><h2><%# Eval("Category_Title") %></h2></asp:Label>
<asp:Label ID="CategoryID" runat="server" Text='<%# Eval("Category_ID")%>' Visible="false" />
<!--News Articles-->
<asp:EntityDataSource ID="NewsDataSource" runat="server" ConnectionString="name=NewsEntities1"
DefaultContainerName="NewsEntities1" EnableFlattening="False"
EntitySetName="tbl_News"
Select="it.[News_ID], it.[Category_ID], it.[Article_Title], it.[Article_Content], it.[Article_Image], it.[Article_Author], it.[Article_CreatedOn]"
Where="it.[Category_ID] = @CategoryID">
<SelectParameters>
<asp:ControlParameter ControlID="CategoryID" Name="CategoryID" DefaultValue="0" Type="Int32" />
</SelectParameters>
</asp:EntityDataSource>
<asp:ListView ID="ListView1" runat="server" DataSourceID="NewsDataSource" GroupItemCount="3">
<LayoutTemplate>
<div ID="groupPlaceholder" runat="server">
</div>
</LayoutTemplate>
<GroupTemplate>
<div ID="itemPlaceholder" runat="server">
</div>
</GroupTemplate>
<EmptyItemTemplate>
<div>
There are currently no articles for this category.
</div>
</EmptyItemTemplate>
<ItemTemplate>
<div>
<a href="#"><%# Eval("Article_Title") %></a><br />
<%# Eval("Article_Content") %><br />
By <%# Eval("Article_Author") %><br /><br />
</div>
</ItemTemplate>
</asp:ListView>
</div>
</ItemTemplate>
</asp:Repeater>
The following code, passes a parameter/value through from a control the nested datasource and then in turn populates the control. This is most useful when creating categories.
This is still work in progress, but hopefully it can be useful for those struggling with this entity framework lark as its not the easiest thing to work with.
<!--Categories-->
<asp:EntityDataSource ID="CategoriesDataSource" runat="server" ConnectionString="name=NewsEntities1"
DefaultContainerName="NewsEntities1" EnableFlattening="False" EntitySetName="tbl_NewsCategories"
Select="it.[Category_ID], it.[Category_Title]">
</asp:EntityDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="CategoriesDataSource">
<ItemTemplate>
<div class="Article">
<asp:Label ID="CategoryHeading" runat="server"><h2><%# Eval("Category_Title") %></h2></asp:Label>
<asp:Label ID="CategoryID" runat="server" Text='<%# Eval("Category_ID")%>' Visible="false" />
<!--News Articles-->
<asp:EntityDataSource ID="NewsDataSource" runat="server" ConnectionString="name=NewsEntities1"
DefaultContainerName="NewsEntities1" EnableFlattening="False"
EntitySetName="tbl_News"
Select="it.[News_ID], it.[Category_ID], it.[Article_Title], it.[Article_Content], it.[Article_Image], it.[Article_Author], it.[Article_CreatedOn]"
Where="it.[Category_ID] = @CategoryID">
<SelectParameters>
<asp:ControlParameter ControlID="CategoryID" Name="CategoryID" DefaultValue="0" Type="Int32" />
</SelectParameters>
</asp:EntityDataSource>
<asp:ListView ID="ListView1" runat="server" DataSourceID="NewsDataSource" GroupItemCount="3">
<LayoutTemplate>
<div ID="groupPlaceholder" runat="server">
</div>
</LayoutTemplate>
<GroupTemplate>
<div ID="itemPlaceholder" runat="server">
</div>
</GroupTemplate>
<EmptyItemTemplate>
<div>
There are currently no articles for this category.
</div>
</EmptyItemTemplate>
<ItemTemplate>
<div>
<a href="#"><%# Eval("Article_Title") %></a><br />
<%# Eval("Article_Content") %><br />
By <%# Eval("Article_Author") %><br /><br />
</div>
</ItemTemplate>
</asp:ListView>
</div>
</ItemTemplate>
</asp:Repeater>
Tuesday, 16 October 2012
Responsive Circles(Border-Radius) CSS3
Heres how to make responsive circles using CSS3, margin is not necessary, but this allows for vertical aligning to also be altered.
Styles:
.circle {
postions:relative;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
width: 50%;
display: table;
margin:10px auto 0;
padding: 30% 10%;
}
.logo {
margin:0 auto;
background:red;
}
.logotext {
text-align:center;
margin: auto 0;
color:#ffffff;
}
Example usages, in Jquery Bootstrap Twitter:
<div class="row">
<div class="span3 offset4">
<div class="logo circle">
<div class="logotext">
Test Logo
</div>
</div>
</div>
</div>
This will allow you to achieve such things as this:
Styles:
.circle {
postions:relative;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
width: 50%;
display: table;
margin:10px auto 0;
padding: 30% 10%;
}
.logo {
margin:0 auto;
background:red;
}
.logotext {
text-align:center;
margin: auto 0;
color:#ffffff;
}
Example usages, in Jquery Bootstrap Twitter:
<div class="row">
<div class="span3 offset4">
<div class="logo circle">
<div class="logotext">
Test Logo
</div>
</div>
</div>
</div>
This will allow you to achieve such things as this:
Monday, 15 October 2012
XML From A Dataset(sql server) To display as XML
Displaying XML from a dataset in this case SQL Server is pretty straight forward.
This is useful if you want to make a call to a page with parameters you may want to pass.
You will need using System.Data.SqlClient; in your class for this.
Heres a quick example:
string connStr = "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand("select * from test", conn);
conn.Open();
DataSet ds = new DataSet();
ds.DataSetName = "YourDataset";
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, "Item");
Response.ContentType = "text/xml";
ds.WriteXml(Response.OutputStream);
}
Remember you could use the sql helper DAL instead of the method above to retrieve the dataset.
This is useful if you want to make a call to a page with parameters you may want to pass.
You will need using System.Data.SqlClient; in your class for this.
Heres a quick example:
string connStr = "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand("select * from test", conn);
conn.Open();
DataSet ds = new DataSet();
ds.DataSetName = "YourDataset";
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, "Item");
Response.ContentType = "text/xml";
ds.WriteXml(Response.OutputStream);
}
Remember you could use the sql helper DAL instead of the method above to retrieve the dataset.
Friday, 12 October 2012
SQL Server ORDER BY Varchar aka Text Field, The Easy Way
When trying to order by a varchar field you can use the following syntax to create a specific order. You can add as many fields as you require to this in the order you wish.
Simply add this to end of your statement:
ORDER BY CASE (MyLevel)
WHEN 'Intermediate' THEN 1
WHEN 'Advanced' THEN 2
WHEN 'Higher' THEN END
In the above example I have a field called MyLevel which is a varchar(50) field which can have 1 those 3 values.
Another annoyance solved hopefully :)
ORDER BY CASE (MyLevel)
WHEN 'Intermediate' THEN 1
WHEN 'Advanced' THEN 2
WHEN 'Higher' THEN END
In the above example I have a field called MyLevel which is a varchar(50) field which can have 1 those 3 values.
Another annoyance solved hopefully :)
Keywords:
case,
order by,
ordering,
SQL Server,
text field,
then,
varchar,
varchar field,
when
Thursday, 11 October 2012
Export Dataset/DataReader .net using 4.0, 4.5 To PDF
When having problems to export to PDF I have recently used a dll called iTextSharp which can be downloaded here and SQL Helper can be found here and once installed the location of the .cs file is \Microsoft Application Blocks for .NET\Data Access v2\Code\CS\Microsoft.ApplicationBlocks.Data
The main problem I had is that I as trying to make a control render using the HtmlTextWriter this result in and error saying that the control should be within the form tags. I think this was due to the way I was rendering the gridviews with sqldatasource controls.
Anwyay this seemed to be a silly way of doing things in the end as I had the datasets returning in the correct format that I wanted already in place, so I decided to use the SQLDataReader. After using this it was a lot more straight forward as I could create loops to display my table in the PDF how I wanted.
You will need to setup the reference to the DLL which will then be accessible.
Your code behind using block should look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
This is the following function I have created which can be called multiple times. The natural progression from this would be to pass sqlparameters into the function and then to the reader. The filename is the output filename that will popup on the browser, so it's good to have the ability to change this on the fly.
protected void ExportToPDF(string storedproc, string filename) {
string attachment = "attachment; filename=" + filename;
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ClearContent();
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
SqlDataReader dr = SqlHelper.ExecuteReader(cn, CommandType.StoredProcedure, storedproc);
htw.Write("<table width='100%'>");
int t;
htw.Write("<tr>");
for (t = 0; t < dr.FieldCount; t++)
{
htw.Write("<td>" + dr.GetName(t) + "</td>");
}
htw.Write("</tr>");
while (dr.Read())
{
htw.Write("<tr>");
for (t = 0; t < dr.FieldCount; t++)
{
htw.Write("<td>" + dr[t].ToString() + "</td>");
}
htw.Write("</tr>");
}
htw.Write("</tr></table>");
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
Example Usage:
ExportToPDF("usp_YourProcedure", "MyTestOutput.pdf");
Notes: If you try to render out the control you will probably get an error like this
"Control 'MainContent_GridView1' of type 'GridView' must be placed inside a form tag with runat=server".
This is the main reason I didnt render out the controls directly, but pulled the dataset in and then created a table. I was also using SQL Datasources with the grids on my page, this could have been done differently, but I wanted the sorting and paging to be automatic also.
Hope this helps those who are struggling with this one. Netferret
The main problem I had is that I as trying to make a control render using the HtmlTextWriter this result in and error saying that the control should be within the form tags. I think this was due to the way I was rendering the gridviews with sqldatasource controls.
Anwyay this seemed to be a silly way of doing things in the end as I had the datasets returning in the correct format that I wanted already in place, so I decided to use the SQLDataReader. After using this it was a lot more straight forward as I could create loops to display my table in the PDF how I wanted.
You will need to setup the reference to the DLL which will then be accessible.
Your code behind using block should look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
This is the following function I have created which can be called multiple times. The natural progression from this would be to pass sqlparameters into the function and then to the reader. The filename is the output filename that will popup on the browser, so it's good to have the ability to change this on the fly.
protected void ExportToPDF(string storedproc, string filename) {
string attachment = "attachment; filename=" + filename;
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ClearContent();
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
SqlDataReader dr = SqlHelper.ExecuteReader(cn, CommandType.StoredProcedure, storedproc);
htw.Write("<table width='100%'>");
int t;
htw.Write("<tr>");
for (t = 0; t < dr.FieldCount; t++)
{
htw.Write("<td>" + dr.GetName(t) + "</td>");
}
htw.Write("</tr>");
while (dr.Read())
{
htw.Write("<tr>");
for (t = 0; t < dr.FieldCount; t++)
{
htw.Write("<td>" + dr[t].ToString() + "</td>");
}
htw.Write("</tr>");
}
htw.Write("</tr></table>");
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
Example Usage:
ExportToPDF("usp_YourProcedure", "MyTestOutput.pdf");
Notes: If you try to render out the control you will probably get an error like this
"Control 'MainContent_GridView1' of type 'GridView' must be placed inside a form tag with runat=server".
This is the main reason I didnt render out the controls directly, but pulled the dataset in and then created a table. I was also using SQL Datasources with the grids on my page, this could have been done differently, but I wanted the sorting and paging to be automatic also.
Hope this helps those who are struggling with this one. Netferret
Keywords:
.net c#,
DAL,
data access layer,
datasets,
iTextSharp,
Output,
PDF,
SQL,
store procedure
Subscribe to:
Posts (Atom)

