Thursday, 10 December 2009

New blog on my own website

From now I will continue blogging on my own website - http://tomi.developmententity.sk/.

Monday, 31 August 2009

Calling service operation in ADO.NET Data Services from Silverlight


Goal:


Call service operation for user authentication programatically from Silverlight codebehind file.



Setting rules for service operation:

public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.None);
config.SetServiceOperationAccessRule("Authenticate", ServiceOperationRights.AllRead);
}





Service operation in ADO.NET Data Service:

[SingleResult]
[WebGet]
public bool Authenticate(string login, string password)
{
var result = from q in this.CurrentDataSource.Users
where q.Login == login && q.Password == password
select q.Login;

if (result.Count() == 1)
{
return true;
}
else
{
return false;
}
}


Calling the service operation from Silverlight:

private PublicService.MyEntities _publicService;

...

private void Button_Login_Click(object sender, RoutedEventArgs e)
{
_publicService = new PublicService.MyEntities(new Uri("PublicService.svc", UriKind.Relative));

_publicService.BeginExecute(new Uri("Authenticate?login='username'&password='password'", UriKind.RelativeOrAbsolute), OnAuthenticationComplete, null);
}

private void OnAuthenticationComplete(IAsyncResult result)
{
bool isAuthenticated = _publicService.EndExecute(result).ToList().First();
}

Sunday, 15 February 2009

JOIN in LINQ

Model situation:


Goal:

Get list of all products with lookup names of its categories, catalogs, subdomains and domains.


LINQ code:


from q in Products
join q1 in Categories on q.CategoryID equals q1.ID
join q2 in Catalogs on q1.CatalogID equals q2.ID
join q3 in SubDomains on q2.SubDomainID equals q3.ID
join q4 in Domains on q3.DomainID equals q4.ID
select new
{
Domain = q4.Domain,
SubDomanin = q3.SubDomain,
Catalog = q2.Catalog,
Category = q1.Category,
Product = q.Title
}


Result

Tuesday, 27 January 2009

Processing Eval in ASP.NET



Recently I was wondering how to process some databinded value inside ASP.NET ListView which datasource have already been set to generic list of news objects with properties like title, description and announced date. The problem was that I wanted to insert a picture before the title when the specific condition, involving processing of announced date property, is fulfilled. Below is the solution that uses method called ImageInsert with Eval parameter and which is defined in codebehind file.



ASP.NET page code:


<asp:ListView runat="server" ID="ListView_News" DataSource="news">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</LayoutTemplate>

<ItemTemplate>
<div class="announcementBlock">
<span style="font-weight: bold; float: left;">
<%# ImageInsert(Eval("DTAnnounced", "{0:d}"))%>
 
<%#Eval("Title") %>
</span>
<span style="font-weight: bold; float: right;">
<%#Eval("DTAnnounced", "{0:d}")%>
</span>
<br />
<br />
<%#Eval("Description") %>
<br />
</div>
<br />
</ItemTemplate>

<EmptyDataTemplate>
No Data!
</EmptyDataTemplate>
</asp:ListView>


C# code in codebehing of ASP.NET page:


protected string ImageInsert(object date)
{
if (Convert.ToDateTime(date).AddDays(4) >= DateTime.Now)
{
return "<img alt=\"News image\" src=\"../Layout/Images/New.gif\" />";
}
else
{
return "";
}
}



Tuesday, 13 January 2009

Simple web crawler in .NET



This web crawler consist of three classes. Program class is used just for testing in console mode. Anchor class serves as a storage object for founded anchors and therefore provide some properties. Crawler class is using two methods:


  • GetHTML - returns HTML page in string format of website which is passed as a parameter.

  • GetAnchorsFromHTML - returns generic collection of anchor tags, which were founded by regular expressions in HTML page.


Some useful links: HttpWebRequest, HttpWebResponse, Regex, Match.



Namespaces used:


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;


Code:


class Program
{
public static void Main()
{
Crawler crawler = new Crawler();

string htmlPage = crawler.GetHTML("http://www.infoq.com/");
List anchors = crawler.GetAnchorsFromHTML(htmlPage);
Console.WriteLine("Anchor collection: " + anchors.Count.ToString() + "\n\n");

foreach (Anchor anchor in anchors)
{
Console.WriteLine(anchor.RawAnchor + "\n");
}

Console.WriteLine("END");
Console.ReadLine();
}
}

public class Crawler
{
public string GetHTML(string website)
{
// send request and get response in form of stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(website);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();

// process stream to memory stream because basic returned stream is not reliable (issues with length...)
MemoryStream memoryStream = new MemoryStream();
byte[] buffer = new byte[2048];
int bytesRead = 0;

do
{
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);

responseStream.Close();

// get string from byte array and encode it in readable format
string htmlPage = "";

if (response.CharacterSet.ToLower().Contains("iso-8859-1") || response.CharacterSet.ToLower().Contains("windows-1250"))
{
htmlPage = Encoding.Default.GetString(memoryStream.ToArray());
}
else
{
htmlPage = Encoding.UTF8.GetString(memoryStream.ToArray());
}

return htmlPage;
}

public List GetAnchorsFromHTML(string htmlPage)
{
List anchors = new List();

// raw anchor
Regex regex = new Regex(@"<a.*?</a>", RegexOptions.IgnoreCase);
// anchor href
Regex regexHref = new Regex("href=(\"|').*?(\"|')", RegexOptions.IgnoreCase);
// anchor text
Regex regexText = new Regex(">.*?</a>", RegexOptions.IgnoreCase);

// matches
Match matchHref;
Match matchText;
Match match = regex.Match(htmlPage);

Anchor anchor;

while (match.Success)
{
anchor = new Anchor();

anchor.RawAnchor = match.Value;

matchHref = regexHref.Match(anchor.RawAnchor);

if (matchHref.Length > 0)
{
anchor.Href = matchHref.Value.Substring(6, matchHref.Value.Length - 7);
}
else
{
anchor.Href = "";
}

matchText = regexText.Match(anchor.RawAnchor);

if (matchText.Length > 0)
{
anchor.Text = matchText.Value.Substring(1, matchText.Value.Length - 5);
}
else
{
anchor.Text = "";
}

anchors.Add(anchor);

match = match.NextMatch();
}

return anchors;
}
}

public class Anchor
{
public string RawAnchor { get; set; }

public string Href { get; set; }

public string Text { get; set; }
}

Saturday, 25 October 2008

How to get list of primary and foreign keys from database (MS SQL Server 2005)


Primary keys:
Information Schema Views (Transact-SQL)
KEY_COLUMN_USAGE (Transact-SQL)
sys.key_constraints (Transact-SQL)

SELECT CONSTRAINT_NAME AS [Constraint Name],
TABLE_NAME AS [PK Table Name],
COLUMN_NAME AS [PK Column Name]
FROM sys.key_constraints
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE
ON INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME = sys.key_constraints.name
WHERE sys.key_constraints.type = 'PK'


Foreign keys:
sys.foreign_key_columns (Transact-SQL)
OBJECT_NAME (Transact-SQL)
COL_NAME (Transact-SQL)

SELECT OBJECT_NAME(constraint_object_id) AS [Constraint Name],
OBJECT_NAME(parent_object_id) AS [FK Table Name],
COL_NAME(parent_object_id, parent_column_id) AS [FK Column Name],
OBJECT_NAME(referenced_object_id) AS [Referenced Table Name],
COL_NAME(referenced_object_id, referenced_column_id) AS [Referenced Column Name]
FROM sys.foreign_key_columns



Tuesday, 2 September 2008

Image reflection in WPF




Eye catchy technique also known as "wet floor". Reflection is used on Image control in example but it can be almost any kind of control which can be reflected. Details:

How to: Create a Reflection

VisualBrush Class

GradientStop Class

LinearGradientBrush Class

ScaleTransform Class




...
<Image Name="image" Width="128" Height="128" Source="Calendar.png" />
<Rectangle Width="128" Height="128">
<Rectangle.Fill>
<VisualBrush Visual="{Binding ElementName=image}" />
</Rectangle.Fill>
<Rectangle.OpacityMask>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FF000000" Offset="3" />
<GradientStop Color="#00000000" Offset="0" />
</LinearGradientBrush>
</Rectangle.OpacityMask>
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="-1" />
<TranslateTransform Y="128" />
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
...