Tuesday 21 December 2010

JQuery Vertical Scroller

useful chunk of code for scrolling a list of something, vertically using JQuery

an example of the list html

<ul id="list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>

this is the jquery

<script type="text/ecmascript">
var list = $("#list");
list.addClass("scrolllist");
list.wrap("<div class=\"clipper_container vert\"></div>").wrap("<div class=\"clipper\"></div>");
var clip = list.parent();
var container = clip.parent();
var items = list.children();
var targetHeight = 0;
items.each(function () { targetHeight += $(this).height() });
var cumulativeHeight = 0;
items.each(function () { cumulativeHeight += $(this).height() });
while (cumulativeHeight < targetHeight * 3) {
items.clone().appendTo(list);
items = list.children();
cumulativeHeight = 0;
items.each(function () { cumulativeHeight += $(this).height() });
}
list.css({ "height": cumulativeHeight + "px" });
var interval = setInterval(function () {
if (clip[0].scrollTop == targetHeight) {
clip[0].scrollTop = 1;
}
else {
clip[0].scrollTop += 1;
}
}, 10);
</script>

and the css

/* css for Scrolling element */

.clipper_container
{
position: relative;
}
.clipper
{
position: relative;
overflow: hidden;
z-index: 2;
height: 493px;
width:144px;
}


.scrolllist
{
position: absolute;
top: 0;
left: 0;
z-index: 1;
overflow: hidden;
margin: 0;
padding: 0;
list-style: none;
height: 493px;
width: 150px;
margin: 0px;
padding: 0px;
}


.scrolllist li
{
list-style-type: none;
padding: 0px;
margin: 0px;
text-align:center;
}

.vert
{
/* wider than clip to position buttons to side */
width: 150px;
height: 493px;
margin-bottom: 1.5em;
}

.clipmain, .scolllistmain, .vertmain
{
height:600px;
}


An additional Development I have made for the scroller is to have a stepped scroll using animate.

To do this simply replace the interval variable stated above with the following
var interval = setInterval(
function () {
var target = targetHeight + list.position().top;
if(target == -50)
{
list.css({top:-50});
}
list.animate({ top: '-=50' }, "fast");
}, 1000);

Friday 17 December 2010

MVC 3 Razor Views and Site Areas

Been working quite a lot over the last few years with MVC and since the release of Razor with MVC3 I have been quite giddy.

The fluid transition you can now have between HTML and programmatic code, has made the all cshtml files a thing of beauty.

There are still some bits I am getting to grips with; the "Areas" functionality now provided for example.

In one case I am creating a mobile site, so creating a new area allows me to create a new _layout.cshtml file to reference a new css file and I found that you can reused any controllers from your parent MVC site, by adding the namespace to the namespaces array in the MapRoute object saving me a lot of work.


public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"ms_default",
"ms/{controller}/{action}/{id}",
new {controller="Home", action = "Index", id = UrlParameter.Optional },
// this defines the namespace for the controllers I have already created in the parent site.
new string[] {"TMS.WEB.Controllers"}
);
}

Then I needed to add all the views from the parent site I wanted. I had to drop in the views even though they are the same for now, as it kept going off to use the layout and views defined in the parent site.

It would have been useful to only have to define as few files as necessary, but I guess I can just copy and replace the files as I maintain the site.

Help with Linked Servers using SQL Scripts

Cannot remember why I needed to do this, think something was being funny when trying to run the Enterprise Manager as a local account rather than a domain account;


EXEC master.dbo.sp_addlinkedserver
@server = 'your linked server name',
@srvproduct = '',
@provider = 'MSDASQL',
@provstr = 'DRIVER={SQL Server};SERVER=MyServer;UID=sa;PWD=sapwd;'


The above creates a default link to the Master Database on your desired server. Once Created go into the properties of the linked server and fill in the "Catalog" field to point to the database you want. 2

Similar sort of Cursor, but slightly different

Got fed up of modifying the previous cursor to do this simpler event.

Basically finds every table in a database and then returns the first row, prefixing the information returned for each table with the tablename.

Saves time running a select statement for each table and useful for finding a table that you know must exist, but isnt clearly named on the database.


declare @command varchar(255)
declare @tablename sysname
declare @count int
DECLARE StatusCursor CURSOR FOR

select a.name from sysobjects a where a.type ='U' order by a.name

Open StatusCursor
Fetch next from StatusCursor into @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
exec ('select top 1 ' + '''' + @tablename + ''', * from ' + @tablename + '')
Fetch next from StatusCursor into @tablename
END
CLOSE StatusCursor
Deallocate StatusCursor

Cursor code for table objects

I had done something cross databases before using sysdatabases, but this time I needed to search for specific text in any column on an table in a known database.



declare @command varchar(255)
declare @tablename sysname
declare @columnname sysname
declare @count int
DECLARE StatusCursor CURSOR FOR

select a.name,b.name from sysobjects a join syscolumns b on a.id = b.id where a.type ='U' order by a.name

Open StatusCursor
Fetch next from StatusCursor into @tablename, @columnname
WHILE @@FETCH_STATUS = 0
BEGIN
if(@columnname = 'FOO1')
begin
print @tablename
end
Fetch next from StatusCursor into @tablename, @columnname
END
CLOSE StatusCursor
Deallocate StatusCursor

Find the index of a list item

It took me a while to find how to do this, but once I had, my eyes will be ever open to the beauty of Linq.

The following code was used in a problem I was working on from Programming Praxis and compares a specific charater to a list of strings

//where row is a List variable and char1 is a charater of interest
var row1 = rows.FindIndex(r => r.Contains(char1) == true)

In the problem above the character can only appear once in the collection.

Understanding Aggregate.. well ish anyway

Combine values from list items
var x is of type collection/list/array


var out = x.Aggregate(<seed,>(acc,item) => acc + item);

acc is the accumulator which is returned
item is each item

At position acc + item, a function can exist to provide extra functionallity.

item is never the first item of the array unless you seed from a blank string.

For example:

var out = x.Aggregate("",(acc,item) => acc + item);

Loading Regex matches to a varaible using Linq

How to get your Regex matches into a Linq variable:

string inString = "ABCDEFGH"
Regex re = new Regex(@"\w{1}");
var list = (from Match m in re.Matches(inString) select m.Value).ToList()


Another easy way to make sure you get words and numbers:


var list = inString.Select(x => 
                {
                    return Regex.Match(x.ToString(), "[a-zA-Z0-9]+");
                });

Conditional String replacement

Found this by accident when doing some linq, but I think this is a nice standard funtion

var x = "A";
Console.Write(String.Format("HELLO WORLD {0}", x.Length == 1 ? x + "X" : x));


Not sure if this works in other version prior to VS2008

One way to return an assembly from a string input

Where T is the interface you have defined to use with the assembly you are passing in and returning;

public class Core
{
public static T GetClass<T>(string Assembly)
{
string[] strAssembly = Assembly.Split(Convert.ToChar("."));
System.Runtime.Remoting.ObjectHandle oObjectHandle;

oObjectHandle = System.Activator.CreateInstance(strAssembly[0].ToString(), Assembly);
T oIinsert = (T)oObjectHandle.Unwrap();
return oIinsert;
}
}

dotNet Mailer

Standard chunk of mailing code.


private System.Net.Mail.MailMessage m;
string Subject = "FOO";
string Message = "F001";
string email = "FOO2";
string strField = "F003";

//PDF,DOC etc
string extn = "PDF";

//application/pdf etc
string strType = "application/pdf";

// This needs filling for attachment to be added
System.IO.MemoryStream memstream;

m = new System.Net.Mail.MailMessage();
m.From = new System.Net.Mail.MailAddress(strEmailAddress);
m.IsBodyHtml = false;
m.Subject = Subject;
m.Body = Message;
System.Net.Mail.MailAddress aTo = new System.Net.Mail.MailAddress(email);
m.To.Add(aTo);
if (memstream.Length != 0)
{
memstream.Position = 0;
m.Attachments.Add(new System.Net.Mail.Attachment(memstream, strField + "." + extn, strType));
}
System.Net.Mail.SmtpClient smServer = new System.Net.Mail.SmtpClient(Configuration.Instance.EmailServer);
smServer.Send(m);

Combine posts

Have a few blogs dedicated to different snippets, think that if I just combine it into this one then I will only need to check one place, and I might find more to write about.

Tuesday 16 February 2010

MVC Mock helper class


public static class MvcMockHelpers
{
public static HttpContextBase FakeHttpContext()
{
var context = new Mock();
var request = new Mock();
var response = new Mock();
var session = new Mock();
var server = new Mock();

context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.SetupGet(ctx => ctx.User.Identity.Name).Returns("TestUser");

return context.Object;
}

public static HttpContextBase FakeHttpContext(string address)
{
HttpContextBase context = FakeHttpContext();
context.Request.SetupRequestUrl(address);
return context;
}

public static void SetFakeControllerContext(this ControllerBase controller)
{
var httpContext = FakeHttpContext();
ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
controller.ControllerContext = context;
}

public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod)
{
Mock.Get(request)
.Setup(req => req.HttpMethod)
.Returns(httpMethod);
}

public static void SetupRequestUrl(this HttpRequestBase request, string address)
{
if (address == null)
{
throw new ArgumentNullException("address");
}

if (!address.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\".");
}

var mock = Mock.Get(request);

mock.Setup(req => req.QueryString)
.Returns(GetQueryStringParameters(address));
mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
.Returns(GetUrlFileName(address));
mock.Setup(req => req.PathInfo)
.Returns(string.Empty);
}

private static string GetUrlFileName(string url)
{
if (url.Contains("?"))
{
return url.Substring(0, url.IndexOf("?", StringComparison.OrdinalIgnoreCase));
}
else
{
return url;
}
}

private static NameValueCollection GetQueryStringParameters(string url)
{
if (url.Contains("?"))
{
NameValueCollection parameters = new NameValueCollection();

string[] parts = url.Split("?".ToCharArray());
string[] keys = parts[1].Split("&".ToCharArray());

foreach (string key in keys)
{
string[] part = key.Split("=".ToCharArray());
parameters.Add(part[0], part[1]);
}

return parameters;
}
else
{
return null;
}
}
}