quinta-feira, 9 de junho de 2011

Integrate Google Graph with .Net

I was working in a dashboard section in my current project and everybody knows that dashboard mean graphs. Surfing on the net I could find a lot of options free and paid. Unfortunately the client decided for a paid one. Anyway I was taking a good look at Google Graph API which is sweet! Then I built my own solution to populate the graph based in my database information.

Check out the Google Graph

Based on this sample I created my own solution, basically before building the graph I'm using the jQuery.ajax() function to perform an ajax request in an ASPX page which will return the data to populate the graph.

This is the code behind from my page which will provide the data.
public partial class chart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Postback
string strReturn = "&Description=string,Year|number,Sales|number,Expenses";
strReturn += "&Data=2004,1000,400|2005,1170,460|2006,860,580|2007,1030,540";
Response.Write(strReturn.Trim());
}
}


As you can see I hardcoded the return value. Anyway you can get the idea about how to build your own return value.

So based in the sample provided by Google I just added few code in the script tag.
ascript type="text/javascript">
var myDataDescription = new Array();
var myData = new Array();

$.ajax({ url: 'chart.aspx', type: 'post', data: 'Type=1',
dataType: "text/html",
success: function (data) {
var desc = data.split('&Description=');
var ind = desc[1].indexOf('&');
var indFinal = (desc[1].length - (ind + 6));
var mydata = desc[1].substr(ind + 6, indFinal);
desc = desc[1].substr(0, ind - 1);
desc = desc.split('|');
mydata = mydata.split('|');

//Generate description array
for (var i = 0; i < desc.length; i++) {
var descInfo = desc[i].split(',');

myDataDescription[i] = new Array();
myDataDescription[i][0] = descInfo[0];
myDataDescription[i][1] = descInfo[1];
}

//Generate data array
for (var i = 0; i < mydata.length; i++) {
var descData = mydata[i].split(',');

myData[i] = new Array(3);
myData[i][0] = descData[0];
myData[i][1] = descData[1];
myData[i][2] = descData[2];
}

},
error: function (err) { alert('failed: ' + err); }
});

google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();

for (var i = 0; i < myDataDescription.length; i++) {
var columnType = myDataDescription[i][0];
var columnName = myDataDescription[i][1];
data.addColumn(columnType, columnName);
}

data.addRows(myData.length);

for (var i = 0; i < myData.length; i++) {
var columnA = myData[i][0];
var columnB = Number(myData[i][1]);
var columnC = Number(myData[i][2]);

data.setValue(i, 0, columnA);
data.setValue(i, 1, columnB);
data.setValue(i, 2, columnC);
}

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240, title: 'Company Performance' });

}


Here you can download the source code.

quarta-feira, 8 de junho de 2011

Prevent page to be cached

Who has never had a problem with the famous back button in the browser?

If you don't, so wait until the QA starts its job!!! I thought I had blocked all the leak in my system, until the QA started hitting the BACK / NEXT button in the browser and broke down everything.

To solve the problem in IE is really easy, but in Firefox can be annoying. Safari as usual, is the best one. Apple is always surprising with their usability!

Past the code bellow in the top of your Page_Load method

//Not to cache in IE
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Not to cache in Firefox
Random rd = new Random();
Response.AddHeader("ETag", rd.Next(1111111, 9999999).ToString());
Response.AddHeader("Pragma", "no-cache");
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();
Response.Expires = -1;

terça-feira, 31 de maio de 2011

Validating FCKEditor with Custom Valitador

Sup Guys,

Today I spent kind of 30 minutes to do something stupid, but worth to share! Maybe I can save your time Googling for it.

Validate a FCKEditor object in client side is really simple and you need to use the FCKEditor Javascript API.

Here is the code of my .aspx file
<fck:FCKeditor ID="txtWinnerpage" runat="server" Value='' BasePath="~/fckeditor/" EditorAreaCSS="/css/editor.css" Width="680px" Height="500px" />

<asp:CustomValidator ID="CustomValidator2" runat="server" ValidationGroup="Tab4" ValidateEmptyText="true" ControlToValidate="txtWinnerpage" ErrorMessage="This is a required field" ClientValidationFunction="cvWinner" Display="Dynamic" ></asp:CustomValidator>

Don't forget to include the property ValidateEmptyText="true" in the CustomValidator control. You can also see that I set the property ClientValidationFunction, this is the name of the JavaScript function the control will call.

Here is the JavaScript code
<script type="text/javascript">

function cvWinner(sender, args) {
var fckBody = FCKeditorAPI.GetInstance('<%=txtWinnerpage.ClientID %>');
args.IsValid = fckBody.GetXHTML(true) != "
";

}
</script>

terça-feira, 19 de outubro de 2010

Conversão de objetos de manipulação de XML

Com o passar dos dias a necessidade de manipular arquivos XML só vem crescendo e com isso nos deparamos com os padrões de objeto LINQ to XML ou DOM e a necessidade de conversão entre eles. Abaixo vou listar alguns tipos de conversões que podem ser úteis no dia a dia.

Converter XElement para XMLNode / Convert XElement to XMLNode
public XmlNode ConverteToXmlNode(XElement xeElement)
{
using (XmlReader xmlReader = xeElement.CreateReader())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
return xmlDoc;
}
}

Converter XDocument para XMLNode / Convert XDocument to XMLNode
public XmlNode ConverteToXmlNode(XDocument xeDocument)
{
using (XmlReader xmlReader = xeDocument.CreateReader())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
return xmlDoc;
}
}

Converter XMLDocument para XDocument / Convert XMLDocument to XDocument
XDocument xdRetornoSefaz = XDocument.Parse(varXmlDocument.OuterXml);

Converter XMLNode para XMLDocument / Convert XMLNode to XMLDocument
XmlDocument varXmlDocument = new XmlDocument();
varXmlDocument.LoadXml(varXmlNode.OuterXml);

segunda-feira, 27 de setembro de 2010

Default Button C# Asp.net

Em muitas páginas web vemos que ao pressionarmos a tecla Enter alguma coisa acontece, sempre algum evento é disparado ou a página é redirecionada para alguma outra página. Essa função é chamada de DefaultButton. Existem maneiras de se implementar essa funcionalidade.

Vejam abaixo como colocar na sua aplicação web utilizando a linguagem de programação C#. 

1) Inicie um novo website e adicione 2 botões e 1 textbox semelhante a imagem abaixo:



2) Altere os objetos para as seguintes propriedades: 

1º botão - Id: btnDefault
               Text: Default

2º botão - Id: btnNaoDefault
               Text: Não Default

1º textbox - Id: txtMensagem
                  width: 250px

3) Clique 2x em cima do botão btnDefault para disparar o evento Click() e informe o seguinte código:


    protected void btnDefault_Click(object sender, EventArgs e)
    {
        txtMensagem.Text = "Passei pelo botão Default";
    }

4) Clique 2x em cima do botão btnNaoDefault para disparar o evento Click() e informe o seguinte código:
    
    protected void btnNaoDefault_Click(object sender, EventArgs e)
    {
        txtMensagem.Text = "Não passei pelo botão Default";
    }


5) No evento Page_Load() da pagina informe a seguinte código:


    protected void Page_Load(object sender, EventArgs e)
    {
        Page.SetFocus(btnNaoDefault);
        Page.Form.DefaultButton = btnDefault.UniqueID;
    }

6) Pronto!! pressione a tecla F5 para compilar sua página. Veja que o foco é redirecionado para o botão "Não Default". Se pressionarmos a tecla Enter veja que mesmo o foco não estando no botão "Default" o metodo Click() do botão Default é disparado.

Bem é isso pessoal, vale a pena lembrar que vale também para web sites que possuem Master Page.

Até a próxima....

quarta-feira, 25 de agosto de 2010

Reflection

Do you wanna read in english?

Para quem nunca ouviu falar Reflection é um mecanismo do .Net que nos permite obter informações de assemblies em runtime(on the fly), ou seja, você consegue instanciar uma Dll em tempo de execução e extrair informações de namespaces, classes, métodos e parâmetros. Também é possível executar métodos em tempo de execução.

Precisei utilizar esse mecanismo em um novo projeto da minha empresa atual que tinha o requisito de executar métodos de uma determinada DLL em tempo de execução.

Durante minhas pesquisas verifiquei também que esse mecanismo é muito utilizado em aplicações que tem instalações de plugin.


----

To whom has never heard about, Reflection is a feature in .Net which enables us to get information about an assembly in runtime(on the fly). So in runtime you can instance a DLL and extract information about namespaces, classes, methods and parameters. You can also run a specific method in runtime.

I needed to use this feature in a new project in my actual company, which one of the requirements was to invoke some methods in runtime.

While I was researching about Reflection I could see this feature is really useful in applications which allows to install plugins.

If u need any more information, please contact me.

----


/*Código Fonte / Source Code*/

//Estou montando os parametros que o método irá receber
object[] myparam = new object[6];
myparam[0] = 90;
myparam[1] = 2;
myparam[2] = @"C:\teste\1.xml";
myparam[3] = @"C:\teste";
myparam[4] = true;
myparam[5] = true;



//Estou chamando o método que ira abrir a DLL em tempo de execução
LoadDll("c:\minhadll.dll", "Namespace.Classe", "Metodo", myparam);


///
/// Abre a dll dinamicamente
///
/// Desenvolvido por: Diego Oliveira - 05/08/2010
/// Nome da DLL
/// Nome da Classe com namespace
/// Nome do Metodo
/// Objeto de parametro
/// Retorna o objeto de retorno do metodo
public static object LoadDll(string strAssemblyName, string strClassName, string strMethodName, object[] objParametros)
{
object returnObject = null;
MethodInfo miMethod = null;
ConstructorInfo ciConstructor = null;
object objResponder = null;
Type tpType = null;
System.Type[] objectTypes;
int intCount = 0;

try
{
//Abre a dll
tpType = System.Reflection.Assembly.LoadFrom(strAssemblyName).GetType(strClassName);

//Pega os parametros passados para identificar o metodo
objectTypes = new System.Type[objParametros.GetUpperBound(0) + 1];
foreach (object objectParameter in objParametros)
{
if (objectParameter != null)
objectTypes[intCount] = objectParameter.GetType();
intCount++;
}

//Referencia o metodo
miMethod = tpType.GetMethod(strMethodName, objectTypes);
ciConstructor = tpType.GetConstructor(Type.EmptyTypes);
objResponder = ciConstructor.Invoke(null);

//Executa o metodo
returnObject = miMethod.Invoke(objResponder, objParametros);

}
catch (Exception ex)
{
throw ex;
}
finally
{
miMethod = null;
ciConstructor = null;
objResponder = null;
tpType = null;
objectTypes = null;
}

return returnObject;
}