Currently Browsing

Posts Tagged ‘ .net ’

Instaladores Habilitados de TDT por Código Postal (JSON + C#)

Pois é, a TDT já anda aí, e por razões que não interessam, precisei de retornar todos os instaladores por cada código postal, cuja PT indica como sendo um instalador habilitado.

Para tal, fiz uma pequena aplicação que enviada um pedido com o código postal, e interpretava o resultado retornado em JSON.

Primeiro tive que criar um ficheiro de texto com todos os códigos postais. Podem fazer download do que usei aqui.

O código poderá não ser o melhor, mas fez o que pretendia e não precisei de me chatear mais com o assunto.

using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    public class CPs
    {
        public string cp4 { get; set; }
        public string cp3 { get; set; }
    }

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GetData();
        }

        private void GetData()
        {
            List<CPs> cps = new List<CPs>();

            TextReader t = new StreamReader(@"C:cps.txt");
            string line = "";
            t.ReadLine();
            while (t.Peek() > 0)
            {
                line = t.ReadLine();
                cps.Add(new CPs() { cp4 = line.Split('-')[0].ToString(), cp3 = line.Split('-')[1].ToString() });
            }

            HttpWebRequest request = null;

            foreach (CPs cp in cps)
            {
                try
                {
                    request = (HttpWebRequest)HttpWebRequest.Create(@"http://tdt.telecom.pt/handlers/installerSearch.ashx?cp4=" + cp.cp4 + "&cp3=" + cp.cp3);
                    request.ContentType = "application/json; charset=utf-8";
                    request.Accept = "application/json, text/javascript, */*";
                    WebResponse response = request.GetResponse();

                    Stream stream = response.GetResponseStream();
                    string json = "";

                    using (StreamReader reader = new StreamReader(stream))
                    {
                        while (!reader.EndOfStream)
                        {
                            json += reader.ReadLine();
                        }
                    }

                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    Dictionary<string, object> x = (Dictionary<string, object>)serializer.DeserializeObject(json);

                    if (x.Count > 0)
                        Response.Write(cp.cp4 + ";" + cp.cp3 + ";" + x["name"].ToString() + ";" + x["phoneNumber1"].ToString() + ";" + x["phoneNumber2"].ToString() + "<br />");

                }
                catch (Exception)
                {

                }

            }
        }

    }

}

Building a Windows Phone 7 Application from Start to Finish

This documentation and accompanying sample application will get you started building a complete application for Windows Phone 7. You will learn about common developer issues in the context of a simple fuel-tracking application for your car named Fuel Tracker. This topic describes things you should know before you start creating your Windows Phone application.

Some of the tasks that you will learn include the following:

From http://msdn.microsoft.com/en-us/library/gg680270%28pandp.11%29.aspx

GridView ShowHeaderWhenEmpty

Até à versão 3.5 da .NET Framework, para mostrarmos os cabeçalhos de uma gridview quando esta não iria conter qualquer resultado, teriamos que recorrer a soluções como esta por exemplo:

List<string> rows = new List<string>(
    new string[] { "line1", "line2", "line3" });

rows.Clear();
if (rows.Count > 0)
{
    gv.DataSource = rows;
    gv.DataBind();
}
else
{
    rows.Add("");
    gv.DataSource = rows;
    gv.DataBind();
    gv.Rows[0].Visible = false;
}

Como é obvio, isto vai sempre executar a condição “else”, mas é apenas para exemplificar como forçar a apresentação do Header na GridView mesmo que o Datasource não contenha qualquer registo.

Na versão 4.0, foi introduzida uma nova propriedade que faz com que o Header seja sempre apresentado sem recorrer a este tipo de truques. A propriedade é a ShowHeaderWhenEmpty.

<asp:GridView runat="server" ID="gv" ShowHeaderWhenEmpty="true">
</asp:GridView>

Criar um ficheiro Zip em C#

Uma forma rápida de criarmos um ficheiro Zip, é recorrendo à classe ZipPackage do WindowsBase.dll.

Para tal, precisamos de adicionar a referencia a esta dll ao nosso projecto, que no meu caso está em “C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.0ProfileClientWindowsBase.dll”.

Podemos criar agora uma classe com um método para criar o ficheiro Zip com os ficheiros que queremos.

public static void CreateZipFile(string zipFilename, List<string> files, CompressionOption compression, bool deleteFilesAfterZip)
        {
            long bsize = 4096;
            byte[] b = new byte[bsize];
            int bytesRead = 0;
            long bytesWritten = 0;
            using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
            {
                foreach (string file in files)
                {
                    Uri uri = PackUriHelper.CreatePartUri(new Uri(file, UriKind.Absolute));
                    if (zip.PartExists(uri))
                        zip.DeletePart(uri);

                    PackagePart part = zip.CreatePart(uri, "", compression);
                    using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        using (Stream dest = part.GetStream())
                        {
                            while ((bytesRead = stream.Read(b, 0, b.Length)) != 0)
                            {
                                dest.Write(b, 0, bytesRead);
                                bytesWritten += bsize;
                            }
                        }
                    }
                }

            }

            if (deleteFilesAfterZip)
                DeleteFiles(files);
        }

Adicionei um parametro (deleteFilesAfterZip) que vai remover todos os ficheiros que foram incluidos no Zip, apenas para me facilitar o trabalho, mas não é obrigatório.

A função DeleteFiles() será algo parecido com isto:

private static void DeleteFiles(List<string> files)
        {
            foreach (string file in files)
            {
                FileInfo f = new FileInfo(file);
                if (!f.Exists)
                    throw new FileNotFoundException();

                f.Delete();
            }
        }

Por fim, para chamarmos a função que cria o ficheiro Zip basta um simples

ZIP.CreateZipFile("c:\xpto.zip", new List<string>() { "c:\xpto.txt", "c:\xpto1.txt" }, System.IO.Packaging.CompressionOption.Normal, false);

Referências:

http://msdn.microsoft.com/en-us/library/system.io.packaging.aspx

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

http://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib.aspx

NBlog : ASP.NET MVC 3.0 Blog Engine

O NLog é um sistema de blogs desenvolvido em ASP.NET MVC 3, Razor, JQuery e C#.

Podem ver em funcionamento em http://chrisfulstow.com/ ou http://blog.appharbor.com/

Este projecto está disponivel para download no CodePlex.

mvcConf – the Virtual ASP.Net MVC Conference

mvcConf

MvcConf is a virtual conference focused on one thing: writing awesome applications on top of the ASP.Net MVC framework. Your brain will explode from taking in so much hard core technical sessions. Sounds fun eh?

This is a community event and we want the best and brightest sharing what they know.

We intend to record each session and make them available online for viewing. We intend to make the videos available free of charge, depending on conference sponsorships.

A mvcConf realizar-se-á dia 8 de Fevereiro às 14h e o registo deve ser feito em http://mvcconf2-esli.eventbrite.com/

Cheat Sheet ADO.NET Entity Framework: Object-Relational Mapping and Data Access

The ADO.NET Entity Framework is a powerful object-relational mapping tool that exists inside Microsoft Visual Studio 2010. This DZone Refcard starts with the basics by showing you how to create a new Data Model. Once you have finished creating the Data Model, author Dane Morgridge moves on to discuss how to insert, query, update, and delete entities. Finishing things up is a section on POCO support with Entity Framework 4.0.

Download

Entity Framework Tutorials

Estão disponiveis no site ASP.NET uma série de tutoriais sobre Entity Framework. Cada um contem ainda um exemplo para download em C# e VB.NET.

The Entity Framework and ASP.NET – Getting Started Part 1
The Entity Framework and ASP.NET – Getting Started Part 2
The Entity Framework and ASP.NET – Getting Started Part 3
The Entity Framework and ASP.NET – Getting Started Part 4
The Entity Framework and ASP.NET – Getting Started Part 5
The Entity Framework and ASP.NET – Getting Started Part 6
The Entity Framework and ASP.NET – Getting Started Part 7
The Entity Framework and ASP.NET – Getting Started Part 8

CodeMash 2011 – WebMatrix Launch Keynote

webmatrix_codemash2011

Já está disponivel no Channel9, o video de lançamento do WebMatrix no CodeMash 2011.

Podem ver o video clicando aqui.

Telerik JustMock Free Edition

JustMock Free Edition is a developer productivity tool designed to make
it easy to create mock objects. JustMock Free Edition cuts your
development time and helps you create better unit tests without
requiring you to change your code. It allows you to perform fast and
controlled tests that are independent of external dependencies like
databases, web services, or proprietary code.

Mais informação e download em http://www.telerik.com/products/mocking/free.aspx

Blogroll