Monday 29 October 2012

Halloween - Jquery, Animate, Top, Left, End of Animation

Here is a quick halloween example, this can obviously be improved, but should help out people get a basic understanding of how to repeat a jquery animation. This is a simple example with a tranparent ghost png.

<style>
body {
background::#000;
overflow-x: hidden;
overflow-y: scroll;
background-color: #000;
}

#ghost {
background:url(img/ghost.png) transparent;
height:128px;
width:128px;
position:absolute;
left:-128px;
overflow:hidden;
}
</style>

<script language="javascript" src="js/jquery-1.8.2.min.js"></script>

<script>

$(document).ready(function () {

function ghost(div){

$(div).css("left","-128px");

// Fading Start
$(div).fadeTo(5000, Math.random(), function() {
// Animation complete.
});
// Fading End

$(div).animate({
left: "+=" + ($("body").width() + 140),
top: (Math.ceil(Math.random()*500)),

},
5000,
function() {
var randomize = Math.ceil(Math.random() * 10000);
setTimeout(function() { ghost(div)},randomize);
}
);

}

ghost("#ghost");

});

</script>

Take note of where "function() {" is within .animate as it allows you to callback once the animation is completed.

Sunday 21 October 2012

GridView Insert Select Delete Fields, Custom

I am still in the process of customising these fields, but to simply move this to the right for example, you can use:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" GridLines="None"
DataKeyNames="Category_ID" DataSourceID="CategoryDataSource"
CssClass="table" onrowcreated="GridView1_RowCreated"
PagerSettings-Mode="NextPreviousFirstLast" AutoGenerateDeleteButton="True">
<Columns>
<asp:BoundField DataField="Category_ID" HeaderText="Category ID"
SortExpression="Category_ID" Visible="false" />
<asp:BoundField DataField="Category_Title" HeaderText="Category Title"
SortExpression="Category_Title" />
<asp:CheckBoxField DataField="Category_Visible" HeaderText="Make Visible?"
SortExpression="Category_Visible" />
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
<asp:CommandField ShowInsertButton="true" />
</Columns>
</asp:GridView>

I will be updated this is due course with more information.


UPDATE:

Error: Delete is disabled for this control.

This was yet another simple but hard to find solution

On your Entitydatasource add EnableDelete="true" EnableInsert="true" EnableUpdate="true"

Now you can update your records as you wish.

Shame this wasnt more obivous as I wasted such a long time on this.






Friday 19 October 2012

CookieParameters and Datasource's

Since the cookie support on DataSource controls for cookies is completely crap, my understanding is it is supposed to pull off the whole cookie(which is no use), if you need to pull of subkey values then doesnt work and it simply passes null.

To add this correctly, put the code in the page_load, this should hit the datasource before it has been rendered to the page.

This is the fastest in the way of 1 line.

Example:

NewsDataSource.WhereParameters.Add(new Parameter("RandomKey", DbType.String, Request.Cookies["CookieName"]["Key"]));

Note: When debugging things along these lines to see what value is passed to the database use sql profiler.

Property or indexer 'System.Web.HttpCookieCollection.this[string]' cannot be assigned to -- it is read only

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"]

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.


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>

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:


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.

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 :)

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