Wednesday, October 20, 2010

Using jquery selectors on server side(C#)

Something that i have been looking for a long time
is to use jquery selectors on the server side.
if found a great solution at fizzler project
fizzler is .NET CSS Selector Engine and you can download it from here.
from fizzler site:
A .NET library to select items from a node tree based on a CSS selector. The default implementation is based on HTMLAgilityPack and selects from HTML documents

all you have to is to download fizzler package
and add reference to this dll files:
- Fizzler.Systems.HtmlAgilityPack.dll
- Fizzler.Systems.XmlNodeQuery.dll
- HtmlAgilityPack.dll

here you can see a useful samples:

HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(
@"<html>
<head></head>
<body>
<div id='content'>
<a target='_blank' href='http://yosi-havia.blogspot.com' class='FirstName'>Yosi</a>
<a href='http://yosi-havia.blogspot.com' class='LastName'>Havia</a>
</div>
</body>
</html>");
HtmlNode document = html.DocumentNode;

//@@@ get all elements with content id in html(result: 1 element)
IEnumerable<HtmlNode> list1 = document.QuerySelectorAll("#content");
List<HtmlNode> lst1 = list1.ToList<HtmlNode>();

//@@@ get all elements with FirstName class name in html(result: 1 element)
IEnumerable<HtmlNode> list2 = document.QuerySelectorAll(".FirstName");
List<HtmlNode> lst2 = list2.ToList<HtmlNode>();

//@@@ get all anchor tags in html(result: 2 elements)
IEnumerable<HtmlNode> list3 = document.QuerySelectorAll("a");
List<HtmlNode> lst3 = list3.ToList<HtmlNode>();

//@@@ get all elements in html(result: 6 elements)
IEnumerable<HtmlNode> list4 = document.QuerySelectorAll("*");
List<HtmlNode> lst4 = list4.ToList<HtmlNode>();

//@@@ get element with attribue name 'target' that starts with '_bl' in html(result: 1 element)
IEnumerable<HtmlNode> list5 = document.QuerySelectorAll("a[target^='_bl']");
List<HtmlNode> lst5 = list5.ToList<HtmlNode>();

Saturday, June 19, 2010

c# window service Debugging - the best way!

Very intresting and complicated issue is how to debug c# window service,
i saw many solutions for that but no one of them made me satisfied.

the best solution for that is to use a simple VS macro, the idea is to start the service and then attach to the process in the same macro.

you can see the macro installation instructions in this post
with a few changes:

Tuesday, March 16, 2010

Create attach to process shortcut in VS 2008

Tools -> Attach to Process... -> wait for the dialog -> < select the process > -> press on attach
who has the time and the patience to follow this step every time we want to debug an internt application.
I'll show u how to attach to process in one shortcut press.
for generate the shortcut, follow the steps below:

  1. Open Visual studio

  2. Press Alt+F11 to open MyMacros

  3. Right click on MyMacros-> Add-> Add existing item and browse to this file(change the file extension to .vb)

  4. Now, we have make a shortcut key to this macro, you should go to Tools -> Options and choose Environment -> Keyboard pane

  5. To find our macro we can search for the word macro in the search text box, and select the macro we want(in my case: Macros.MyMacros.AttachingToProcess.AttachToInternetApp)

  6. Choose a shortcut keys for this macro and insert them in the 'Press shortcut keys' text box, i choose ctrl+\ (u have to press them together)

  7. Press on Assign button, and ok, that's all, we finished


Friday, February 12, 2010

Create secure form without captcha

Usually when we want to create a secure form that computer programs cannot pass we use the captcha program.
captcha has a lot of disadvantages, when the main disadvantages is that the captcha is heavy, bother, and make users to run away from our form.
in the idea that i'll show in this post the user cannot notice in any difference from unsecured form.
the steps for the very simple solution is

1. generate a random names to inputs in the form
2. save the names in the session collection at the server side
3. after the user submits the forn, take the inputs names fron rhe session
4. the the inputs values from the request collection with the key names from the session

take a look at this simple example at asp .net but it will work in every server side language:
---------------------------------------------------------------------------------------
the server side code

public partial class _Default : System.Web.UI.Page
{
public string UserNameKey;
public string PasswordKey;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["UserNameKey"] = UserNameKey = Guid.NewGuid().ToString();
Session["PasswordKey"] = PasswordKey = Guid.NewGuid().ToString();
}
}
protected void lnkSend_Click(object sender, EventArgs e)
{
if (Session["UserNameKey"] != null
&& Session["PasswordKey"] != null)
{
string UserNameValue = Request[Session["UserNameKey"].ToString()];
string PasswordValue = Request[Session["PasswordKey"].ToString()];
}
}
}


the html code

<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
User name: <input type="text" name="<%=UserNameKey%>" />
<br />
Password: <input type="password" name="<%=PasswordKey%>" />
<br />
<asp:LinkButton ID="lnkSend" runat="server"
onclick="lnkSend_Click" >Send</asp:LinkButton>
</form>
</body>
</html>

Monday, September 14, 2009

Simple xslt example

In this post i'll show how 2 make a simple xsl transform.
In addition i'll show how to use this xsl elements:

1. XsltArgumentList - pass arguments to the xslt
2. Encoding - declare the outgoing xml encoding
3. xsl:value-of - take the value(inner text) of node
4. xsl:copy-of - copy the inner xml of node
5. xsl:for-each - loop through same nodes
6. xsl:sort - sort nodes by specified node

and in the end of the post there is a c# thread safety class to make xsl transforms

so, this is the origin xml file(Person.xml):

<hPerson>
<Header>

<FirstName>Yosi</FirstName>
<LastName>Havia</LastName>
<Age>30</Age>
<Education>BA</Education>
</Header>
<hChildren>
<hChild>
<hName>Carol</hName>
<hAge>13</hAge>
</hChild>
<hChild>
<hName>Angela</hName>
<hAge>15</hAge>
</hChild>
<hChild>
<hName>Benjamin</hName>
<hAge>17</hAge>
</hChild>
</hChildren>
</hPerson>


and this is the xslt file(Person.xslt):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes" omit-xml- declaration="yes"/>
<xsl:param name="Gender"></xsl:param>
<xsl:template match="/">
<Person>
<Gender>
<xsl:choose>
<xsl:when test="$Gender='1'">
Male
</xsl:when>
<xsl:otherwise>
Female
</xsl:otherwise>
</xsl:choose>
</Gender>
<xsl:copy-of select="/hPerson/Header"/>
<Data>
<Children>
<xsl:for-each select="/hPerson/hChildren/hChild">
<xsl:sort select="hName" />
<Child>
<FirstName>
<xsl:value-of select="hName"/>
</FirstName>
<Age>
<xsl:value-of select="hAge"/>
</Age>
</Child>
</xsl:for-each>
</Children>
</Data>
</Person>
</xsl:template>
</xsl:stylesheet>

the output xml look like this:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
<Gender>
Male
</Gender>
<Header>
<FirstName>Yosi</FirstName>
<LastName>Havia</LastName>
<Age>30</Age>
<Education>BA</Education>
</Header>
<Data>
<Children>
<Child>
<FirstName>Angela</FirstName>
<Age>15</Age>
</Child>
<Child>
<FirstName>Benjamin</FirstName>
<Age>17</Age>
</Child>
<Child>
<FirstName>Carol</FirstName>
<Age>13</Age>
</Child>
</Children>
</Data>
</Person>

this is a thread safety c# class to make xsl transforms

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace XSLT
{
class XsltObj
{
protected static XslCompiledTransform _oXslTransform;
protected static object _oSyncXsl = new object();
public string FormatXmlWrapper(string sEncoding, XsltArgumentList
oXsltArgumentList,XmlDocument oOriginXmlDoc, string sXslPath)
{
string sRetVal = null;
if (_oXslTransform == null)
{
LoadXslWrapper(sXslPath, ref _oXslTransform, ref _oSyncXsl);
}
//@@@ make the transform
try
{
sRetVal = TransformData(sEncoding, _oXslTransform, oOriginXmlDoc,
oXsltArgumentList);
}
catch (Exception ex)
{
throw ex;
}
return sRetVal;
}
protected void LoadXslWrapper(string sXslPath,
ref XslCompiledTransform oXslTransform, ref object oSyncXsl)
{
lock (oSyncXsl)
{
if (oXslTransform == null)
{
XslCompiledTransform oTempXslTransform =
new XslCompiledTransform();
//@@@ get the xml path from configuration
LoadXsl(sXslPath, ref oTempXslTransform);
oXslTransform = oTempXslTransform;
}
}
}
protected void LoadXsl(string sXslPath, ref XslCompiledTransform
oXslCompiledTransform)
{
//@@@ load the xsl document(only once)
XmlDocument xslDocument = new XmlDocument();
XmlUrlResolver urlResolver = new XmlUrlResolver();
urlResolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
xslDocument.XmlResolver = urlResolver;
try
{
//@@@ load the xsl document
xslDocument.Load(sXslPath);
XPathNavigator oXPathNavigator = xslDocument.CreateNavigator();
oXslCompiledTransform.Load(oXPathNavigator,
XsltSettings.TrustedXslt, urlResolver);
}
catch (Exception ex)
{
throw ex;
}
}
protected string TransformData(string sEncoding, XslCompiledTransform
oXslTransform, XmlDocument xmlDocument, XsltArgumentList argumentList)
{
StringBuilder sb = new StringBuilder();
string sDeclaration;
//@@@ decide the xml declaration up to the Encoding
if (string.IsNullOrEmpty(sEncoding))
sDeclaration = "version=\"1.0\"";
else
sDeclaration = "version=\"1.0\" encoding=\"" + sEncoding + "\"";
//@@@ make the xsl Transform
using (XmlWriter output = XmlWriter.Create(sb))
{
output.WriteProcessingInstruction("xml", sDeclaration);
XPathNavigator oXPathNavigator = xmlDocument.CreateNavigator();
oXslTransform.Transform(oXPathNavigator, argumentList, output);
return sb.ToString();
}
}
}
}

to activate this object use this code:

static void Main(string[] args)
{
XsltObj oXsltObj = new XsltObj();
XsltArgumentList oXsltArgumentList = GetXsltArguments();
XmlDocument oXmlDocument = new XmlDocument();
string sXmlPath = @"Person.xml";
string sXslPath = @"Person.xslt";
oXmlDocument.Load(sXmlPath);
string sXml = oXsltObj.FormatXmlWrapper("UTF-8", oXsltArgumentList,
oXmlDocument, sXslPath);
}
protected static XsltArgumentList GetXsltArguments()
{
//@@@ create the arguments for the xsl
XsltArgumentList list = new XsltArgumentList();
list.AddParam("Gender", string.Empty, "1");
return list;
}

Wednesday, August 19, 2009

force download of remote file

Many times we want 2 enable 2 users to download files from our web site
just put this function in the Page_Load function and then the users will be enable to download remote files from any web site (note that the function parameter is a virtual path!):

private void forceDownloadRemoteFile(string sFileVirtualPath)
{
string sFileName = System.IO.Path.GetFileName(sFileVirtualPath);
WebClient oWebClient = new WebClient();
MemoryStream oMemoryStream;
try
{
byte[] bytes = oWebClient.DownloadData(sFileVirtualPath);
oMemoryStream = new MemoryStream(bytes);
}
finally
{
oWebClient.Dispose();
}
BinaryReader oBinaryReader = new BinaryReader(oMemoryStream);
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition",
string.Format("attachment;filename={0}", sFileName));
Response.BinaryWrite(oBinaryReader.ReadBytes((int)oMemoryStream.Length));

oBinaryReader.Close();

Response.Flush();
Response.End();
}

To execute this function u can use this code:

protected void Page_Load(object sender, EventArgs e)
{
string sFileVirtualPath = @"http://localhost/TryWebSite/TextFile.txt";
forceDownloadRemoteFile(sFileVirtualPath);
}

Saturday, August 8, 2009

How to transform between object and xml in c#

Hi,
Many times we need 2 make transforms object to xml and transform xml to object.
there is a very simple way in XmlSerializer class, we just have to call serialize or Deserialize function and we can get what want. I'll explain it by example:


let's say that we have RootData class:

public class RootData
{
public HeaderElement Header;
public List SubjectsList;
}
public class HeaderElement
{
public int DataType;
}
public class Subject
{
public string SubjectName;
public int SubjectID;
public int SubjectType;
}

and we need to make transforms with this xml:

<?xml version="1.0" encoding="utf-8"?>
<RootData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Header>
<DataType>1</DataType>
</Header>
<SubjectsList>
<Subject>
<SubjectName>Name1</SubjectName>
<SubjectID>1</SubjectID>
<SubjectType>1</SubjectType>
</Subject>
<Subject>
<SubjectName>Name2</SubjectName>
<SubjectID>2</SubjectID>
<SubjectType>2</SubjectType>
</Subject>
<Subject>
<SubjectName>Name3</SubjectName>
<SubjectID>3</SubjectID>
<SubjectType>3</SubjectType>
</Subject>
</SubjectsList>
</RootData>


The function 2 make transform from object to xml is:

public string SerializeObject(Type oType, object oRootData)
{
//@@@ Create xml from the object
MemoryStream oMemoryStream = null;
XmlTextWriter oXmlTextWriter = null;
string sXml = null;
try
{
oMemoryStream = new MemoryStream();
XmlSerializer oXmlSerializer = new XmlSerializer(oType);
oXmlTextWriter = new XmlTextWriter(oMemoryStream, Encoding.UTF8);
oXmlSerializer.Serialize(oXmlTextWriter, oRootData);
oMemoryStream = (MemoryStream)oXmlTextWriter.BaseStream;
UTF8Encoding oUTF8Encoding = new UTF8Encoding();
sXml = oUTF8Encoding.GetString(oMemoryStream.ToArray());
}
catch (Exception)
{
throw;
}
finally
{
if (oMemoryStream != null)
oMemoryStream.Close();
if (oXmlTextWriter != null)
oXmlTextWriter.Close();
}
return sXml;
}

The function 2 make transform from xml to object is:

public object DeserializeObject(Type oType, string sXml)
{
//@@@ Create object from the xml
MemoryStream oMemoryStream = null;
object oRootData = null;
try
{
XmlSerializer oXmlSerializer = new XmlSerializer(oType);
UTF8Encoding oUTF8Encoding = new UTF8Encoding();
Byte[] Bytes = oUTF8Encoding.GetBytes(sXml);
oMemoryStream = new MemoryStream(Bytes);
oRootData = oXmlSerializer.Deserialize(oMemoryStream);
}
catch (Exception)
{
throw;
}
finally
{
if (oMemoryStream != null)
oMemoryStream.Close();
}
return oRootData;
}

Before u run this example, u can fill your object with this function:

public RootData CreateData()
{
RootData oRootData = new RootData();
HeaderElement oHeaderElement = new HeaderElement();
oHeaderElement.DataType = 1;
oRootData.Header = oHeaderElement;

Subject oSubject1 = new Subject();
oSubject1.SubjectID = 1;
oSubject1.SubjectName = "Name1";
oSubject1.SubjectType = 1;

Subject oSubject2 = new Subject();
oSubject2.SubjectID = 2;
oSubject2.SubjectName = "Name2";
oSubject2.SubjectType = 2;

Subject oSubject3 = new Subject();
oSubject3.SubjectID = 3;
oSubject3.SubjectName = "Name3";
oSubject3.SubjectType = 3;

List Subjects = new List();
Subjects.Add(oSubject1);
Subjects.Add(oSubject2);
Subjects.Add(oSubject3);

oRootData.SubjectsList = Subjects;
return oRootData;
}

And run this code to execute the transform:

RootData oRootData = CreateData();
string sXml = SerializeObject(typeof(RootData), oRootData);
oRootData = (RootData)DeserializeObject(typeof(RootData), sXml);


In this case when every data member trnsform 2 xml node we dont have to change or add nothing in the class, but there is a few useful attributes that we can use (just add it above the data member class):

  • [XmlElement("<Xml Node Name>")] - by default, the XmlSerializer uses the data member name as the xml node name, if u want 2 change it - use this attribute

  • [XmlElement(("<Xml Node Name>"), IsNullable = false)] - says that if the data member value is null it will not appear in the transformed xml

  • [XmlAttribute] - use it when u want that the data member output will be xml attribute and not xml node