Custom Search
Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

June 25, 2008

Como almacena y administra Facebook las fotos

Encontre en Slashdot una presentación que se hizo en el ACM de Stanford, acerca de como hace Facebook para almacenar eficientemente millones de fotos.

Datos interesantes:

  • Fabook almacena ~6.5 billones de Fotos (6.5 x 1,000,000,000,000)
  • Cada foto está en 4 - 5 tamaños, lo que da ~30 billones de archivos.
  • Son cerca de 540 TB
  • En el mayor pico, se sirven ~475,000 imagenes por segundo.

Aqui puedes encontrar dicha presentación en linea.

April 8, 2008

Google App Engine

Entre todo el conjunto de herramientas que ha desarrollado Google, ahora están liberando en versión "Preview" el Google App Engine. El Google App Engine es un conjunto de herramientas que permite ejecutar aplicaciones web bajo la infraestructura de Google. Existe en el site oficial todo lo necesario para hacer la implmentación así como ejemplos.

Lo necesario para correr este tipo de applicaciones:

  • No es necesario montar nada. Google App Engine tiene un ambiente de applicación integrado.
  • Es facil de escalar. En Google App Engine es sencillo construir aplicaciones que sean escalables y puedan crecer hasta contar con millones de usuarios.
  • Es de libre acceso. Cada aplicaci'on en Google App Engine puede usar hasta 500 MB de almacenamiento y suficiente anocho de banda y CPU para tener 5 millones de visitas en un mes.

El primer post en el blog que han creado para tal efecto:
Introducing Google App Engine + our new blog
from Google App Engine Blog by Karen
Posted by Paul McDonald, Product Manager

At tonight's Campfire One we launched a preview release of Google App Engine -- a developer tool that enables you to run your web applications on Google's infrastructure. The goal is to make it easy to get started with a new web app, and then make it easy to scale when that app reaches the point where it's receiving significant traffic and has millions of users.

Google App Engine gives you access to the same building blocks that Google uses for its own applications, making it easier to build an application that runs reliably, even under heavy load and with large amounts of data. The development environment includes the following features:

* Dynamic webserving, with full support of common web technologies
* Persistent storage (powered by Bigtable and GFS with queries, sorting, and transactions)
* Automatic scaling and load balancing
* Google APIs for authenticating users and sending email
* Fully featured local development environment

Google App Engine packages these building blocks and takes care of the infrastructure stack, leaving you more time to focus on writing code and improving your application.

Today's launch is a preview release -- we're by no means feature-complete, and we're giving you early access because we really want your feedback. This preview of Google App Engine is available for the first 10,000 developers who sign up, and we plan to increase that number in near future.

During this preview period, applications are limited to 500MB of storage, 200M megacycles of CPU per day, and 10GB bandwidth per day. We expect most applications will be able to serve around 5 million pageviews per month. In the future, these limited quotas will remain free, and developers will be able to purchase additional resources as needed.

If you'd like to try it out, sign up for access to the preview release and then download the SDK to get started. The best place to give us feedback is in the discussion group. Future announcements from us will appear there and/or this blog.



Blog...

August 2, 2007

Barra de % en AJAX

Echenle un ojo a este post de xyberneticos, se trata de una barra para presentar el procentaje de avance de una tarea utilizando AJAX.

Link

Preview:

July 13, 2007

Uso del PNG

Acabo de leer este post, muy bueno para todos aquellos que se dedican al desarrollo web, webmasters, etc, etc, etc. La nota habla acerca del uso de archivos PNG.

Link:
http://www.edenahp.net/png/


Visto en: http://www.espartha.com

May 7, 2007

Estrategias para enseñar lenguajes de programación

En busca de nuevas estrategias para enseñar lenguajes de programación

Fuente: http://www.conocimientoenlinea.com/content/view/52/50/
Ingeniera Jakeline Marcos Abed
Profesora del Departamento de Ciencias Computacionales,
Tecnológico de Monterrey
jakeline@itesm.mxEsta dirección de correo electrónico está protegida contra los robots de spam, necesita tener Javascript activado para poder verla

 

Ciencia

Las estrategias, técnicas y herramientas relacionadas con la enseñanza han evolucionado a lo largo del tiempo. En particular, enseñar lenguajes de programación siempre ha constituido un reto, debido a la naturaleza abstracta de dichos lenguajes y al desarrollo del pensamiento lógico en el estudiante.  

Cuando se trata de aprender un nuevo idioma, es necesario estudiar las reglas gramaticales, si es que después se quiere escribir correctamente en dicho idioma. De igual forma, para escribir un programa en lenguaje computacional, es necesario aprender primero las reglas gramaticales, desarrollando al mismo tiempo la lógica; es decir, la forma en la que se ha de solucionar el problema, para posteriormente generalizar una solución mediante la utilización de la computadora.   

De ahí que los estudiantes que estudian por primera vez un lenguaje de programación, se enfrentan con varios dilemas:

Comprender los conceptos nuevos.

Memorizar estrictas reglas de sintaxis.

Comprender el problema por solucionar  (a veces ni siquiera entienden el problema…).

Establecer los pasos que se han de seguir para solucionar el problema en cuestión.

Para superar este tipo de barreras, y gracias a los avances en el área de tecnología, se han desarrollado herramientas gráficas muy amigables, que facilitan la introducción al maravilloso mundo de la programación.

Una de estas herramientas se llama Alice ©, creada por la Universidad de Carnegie Mellon, y utilizada exitosamente en el Tec de Monterrey, en los cursos base de programación.    

APRENDIZAJE DE LA "JERGA" MEDIANTE LA UTILIZACIÓN
DE MUNDOS VIRTUALES

Al iniciar un curso de programación, puede existir en el profesor la duda de por dónde empezar.

Algunos cursos empiezan por el manejo de variables y tipos de datos; otros, con el manejo de algoritmos en la solución de problemas, mientras que otros empiezan por conceptos de clases y objetos.

Esto ha dado pie a diferentes discusiones e investigaciones, que no serán tratadas en este momento, ya que sería como hablar de política o religión.

Sin embargo, una cosa es cierta: hacer un curso de programación con altas dosis de teoría hace que el estudiante pierda interés en la clase, y al no existir interés, no existe motivación por aprender.

Y es aquí donde Alice entra en acción: Alice agrega un factor de motivación en el alumno.

Al haber más motivación en la clase, se incrementa el deseo por aprender, y entre más se comprende algo, menos se tiene que memorizar, y como se entiende más, gusta más, haciendo de esto un círculo virtuoso.
Alice es una herramienta gráfica que permite la creación de mundos virtuales. En este ambiente de edición de escenarios, es posible recrear pequeñas historias con actores de tipo caricatura, que van desde animalitos del bosque hasta personajes del viejo oeste, o criaturas propias de videojuegos.

SECUENCIA DE ACCIONES
Entonces, el estudiante crea una historia, escoge los actores, escoge el escenario y arma la trama, para lo cual diseña una secuencia de acciones que resolverán un pequeño problema. Es en este momento cuando el estudiante empieza a estructurar sus ideas, y da orden y secuencia a las acciones de los objetos involucrados.

Tomando como ejemplo la imagen mostrada abajo, si el sheriff quiere llegar al caballo, tiene que caminar hacia él. Pero la acción de caminar está compuesta por: subir la pierna derecha, bajar la pierna derecha, subir la pierna izquierda, bajar la pierna izquierda, avanzando medio metro en cada paso. ¿Cuántas veces va a hacer esto? No sabemos. El sheriff entrará en un proceso repetitivo, ya que caminará mientras se encuentre lejos del caballo.
De esta forma, Alice permite un aprendizaje activo que se puede asociar con la realidad, incorporando conceptos de programación, tales como uso de condiciones y repeticiones, o de programación orientada a objetos, como uso y creación de métodos, propiedades de un objeto, abstracción y herencia,  o incluso manejo de eventos.

Todo esto con la facilidad de "arrastrar y soltar", sin necesidad de aprender la gramática de ningún lenguaje computacional.

Ciencia ENTENDIDOS LOS CONCEPTOS,
VAMOS AHORA POR EL LENGUAJE

Una vez que el estudiante se ha familiarizado con los conceptos principales de programación, en un ambiente controlado como Alice,  es momento de migrar hacia un lenguaje de programación orientada a objetos, siempre con el apoyo de los conceptos aprendidos previamente.

De esta forma, llevaremos a los alumnos a un segundo nivel, en donde al explicar los estatutos propios del lenguaje de programación, todos estaremos utilizando el mismo vocabulario. Siguiendo con el ejemplo del Sheriff y el caballo, ahora podemos hablar de tipos de datos dentro de una clase específica: la clase Sheriff. Sabemos que la edad del Sheriff puede ser representada por un entero; la estatura, por un valor con decimales, y el nombre, por una cadena de caracteres.

Además, podemos hablar de acciones o métodos definidos para la clase Sheriff,  y podemos darnos cuenta que serán diferentes de los métodos o acciones definidos para la clase Caballo.

Una vez aprendidos los conceptos y el lenguaje, y habiendo ya trabajado en la solución de pequeños problemas, ahora sí nos dedicaremos por completo a la lógica de programación para resolver problemas más complejos.

Este tercer nivel es el que tiene mayor importancia dentro del curso, pero es difícil llegar a él si no se han comprendido bien los conceptos y las reglas de las primeras dos fases.
También en este sentido Alice nos ayudará, ya que el manejo de estatutos de control es incorporado desde los primeros ejemplos del curso.

CONCLUSIONES
Aunque herramientas como Alice no garantizan el aprendizaje de los lenguajes de programación, sí motivan y ayudan al estudiante a comprender conceptos que de otra forma serían más difíciles de entender.

Así, si consideramos el desarrollo de aplicaciones complejas, utilizando lenguajes de programación orientada a objetos, como una competencia eje de las carreras de tecnología, debemos privilegiar el fortalecimiento de las habilidades del pensamiento a través de la práctica continua e incremental, utilizando actividades creativas y retos interesantes de programación, dejando tiempo suficiente para pensar.

May 2, 2007

Top 10 Application Security Vulnerabilities in Web.config Files - Part One

A la hora de hacer nuestras aplicaciones web comúnmente nos dejamos llevar y usamos las mismas configuraciones
al llevar nuestra aplicación a producción. En esta ocasión Bryan Sullivan nos habla de 10 puntos importantes
que no debemos olvidar al momento de poner en producción.

Fuente: http://www.codeproject.com/useritems/web-based-applications.asp

Ahora a ponerlas en práctica!! :D
 

Top 10 Application Security Vulnerabilities in Web.config Files - Part One
By Bryan_Sullivan.



In part one of this two part article, you will learn about five of the top ten "worst offenders" of misconfigurations of application security that can cause overall problems for ASP.NET Web-based applications. Learn more about how to secure the Web.config files of an ASP.NET application.

These days, the biggest threat to an organization's network security comes from its public Web site and the Web-based applications found there. Unlike internal-only network services such as databases-which can be sealed off from the outside via firewalls-a public Web site is generally accessible to anyone who wants to view it, making application security an issue. As networks have become more secure, vulnerabilities in Web applications have inevitably attracted the attention of hackers, both criminal and recreational, who have devised techniques to exploit these holes. In fact, attacks upon the Web application layer now exceed those conducted at the network level, and can have consequences which are just as damaging.

Some enlightened software architects and developers are becoming educated on these threats to application security and are designing their Web-based applications with security in mind. By "baking in" application security from the start of the development process, rather than trying to "brush it on" at the end, you are much more likely to create secure applications that will withstand hackers' attacks. However, even the most meticulous and security-aware C# or VB.NET code can still be vulnerable to attack if you neglect to secure the Web.config configuration files of your application. Incorrectly configured Web-based applications can be just as dangerous as those that have been incorrectly coded. To make matters worse, many configuration settings actually default to insecure values.

This article lists five of the "worst offenders" of misconfigurations of application security that are universally problematic for all ASP.NET Web-based applications. Part two of this article will list an additional five misconfigurations that are specifically applicable to ASP.NET sites that use Web Forms authentication. So without further ado, let's get started!

1. Custom Errors Disabled


When you disable custom errors as shown below, ASP.NET provides a detailed error message to clients by default.

Vulnerable configuration:

<configuration>

<system.web>

<customErrors mode="Off">

Secure configuration:

<configuration>

<system.web>

<customErrors mode="RemoteOnly">

In itself, knowing the source of an error may not seem like a risk to application security, but consider this: the more information a hacker can gather about a Web site, the more likely it is that he will be able to successfully attack it. An error message can be a gold mine of information to an attacker. A default ASP.NET error message lists the specific versions of ASP.NET and the .NET framework which are being used by the Web server, as well as the type of exception that was thrown. Just knowing which Web-based applications are used (in this case ASP.NET) compromises application security by telling the attacker that the server is running a relatively recent version of Microsoft Windows and that Microsoft Internet Information Server (IIS) 6.0 or later is being used as the Web server. The type of exception thrown may also help the attacker to profile Web-based applications; for example, if a "SqlException" is thrown, then the attacker knows that the application is using some version of Microsoft SQL Server.

You can build up application security to prevent such information leakage by modifying the mode attribute of the <customErrors> element to "On" or "RemoteOnly." This setting instructs Web-based applications to display a nondescript, generic error message when an unhandled exception is generated. Another way to circumvent this application security issue is to redirect the user to a new page when errors occur by setting the "defaultRedirect" attribute of the <customErrors> element. This approach can provide even better application security because the default generic error page still gives away too much information about the system (namely, that it's using a Web.config file, which reveals that the server is running ASP.NET).

2. Leaving Tracing Enabled in Web-Based Applications


The trace feature of ASP.NET is one of the most useful tools that you can use to ensure application security by debugging and profiling your Web-based applications. Unfortunately, it is also one of the most useful tools that a hacker can use to attack your Web-based applications if it is left enabled in a production environment.

Vulnerable configuration:

<configuration>

<system.web>

<trace enabled="true" localOnly="false">

Secure configuration:

<configuration>

<system.web>

<trace enabled="false" localOnly="true">

When the <trace> element is enabled for remote users of Web-based applications (localOnly="false"), any user can view an incredibly detailed list of recent requests to the application simply by browsing to the page "trace.axd." If a detailed exception message is like a gold mine to a hacker looking to circumvent application security, a trace log is like Fort Knox! A trace log presents a wealth of information: the .NET and ASP.NET versions that the server is running; a complete trace of all the page methods that the request caused, including their times of execution; the session state and application state keys; the request and response cookies; the complete set of request headers, form variables, and QueryString variables; and finally the complete set of server variables.

A hacker looking for a way around application security would obviously find the form variable histories useful because these might include email addresses that could be harvested and sold to spammers, IDs and passwords that could be used to impersonate the user, or credit card and bank account numbers. Even the most innocent-looking piece of data in the trace collection can be dangerous in the wrong hands. For example, the "APPL_PHYSICAL_PATH" server variable, which contains the physical path of Web-based applications on the server, could help an attacker perform directory traversal attacks against the system.

The best way to prevent a hacker from obtaining trace data from Web-based applications is to disable the trace viewer completely by setting the "enabled" attribute of the <trace> element to "false." If you have to have the trace viewer enabled, either to debug or to profile your application, then be sure to set the "localOnly" attribute of the <trace> element to "true." That allows users to access the trace viewer only from the Web server and disables viewing it from any remote machine, increasing your application security.

3. Debugging Enabled


Deploying Web-based applications in debug mode is a very common mistake. Virtually all Web-based applications require some debugging. Visual Studio 2005 will even automatically modify the Web.config file to allow debugging when you start to debug your application. And, since deploying ASP.NET applications is as simple as copying the files from the development folder into the deployment folder, it's easy to see how development configuration settings can accidentally make it into production, compromising application security.

Vulnerable configuration:

<configuration>

<system.web>

<compilation debug="true">

Secure configuration:

<configuration>

<system.web>

<compilation debug="false">

Like the first two application security vulnerabilities described in this list, leaving debugging enabled is dangerous because you are providing inside information to end users who shouldn't have access to it, and who may use it to attack your Web-based applications. For example, if you have enabled debugging and disabled custom errors in your application, then any error message displayed to an end user of your Web-based applications will include not only the server information, a detailed exception message, and a stack trace, but also the actual source code of the page where the error occurred.

Unfortunately, this configuration setting isn't the only way that source code might be displayed to the user. Here's a story that illustrates why developers shouldn't concentrate solely on one type of configuration setting to improve application security. In early versions of Microsoft's ASP.NET AJAX framework, some controls would return a stack trace with source code to the client browser whenever exceptions occurred. This behavior happened whenever debugging was enabled, regardless of the custom error setting in the configuration. So, even if you properly configured your Web-based applications to display non-descriptive messages when errors occurred, you could still have unexpectedly revealed your source code to your end users if you forgot to disable debugging.

To disable debugging, set the value of the "debug" attribute of the <compilation> element to "false." This is the default value of the setting, but as we will see in part two of this article, it's safer to explicitly set the desired value rather than relying on the defaults to protect application security.

4. Cookies Accessible through Client-Side Script


In Internet Explorer 6.0, Microsoft introduced a new cookie property called "HttpOnly." While you can set the property programmatically on a per-cookie basis, you also can set it globally in the site configuration.

Vulnerable configuration:

<configuration>

<system.web>

<httpCookies httpOnlyCookies="false">

Secure configuration:

<configuration>

<system.web>

<httpCookies httpOnlyCookies="true">

Any cookie marked with this property will be accessible only from server-side code, and not to any client-side scripting code like JavaScript or VBScript. This shielding of cookies from the client helps to protect Web-based applications from Cross-Site Scripting attacks. A hacker initiates a Cross-Site Scripting (also called CSS or XSS) attack by attempting to insert his own script code into the Web page to get around any application security in place. Any page that accepts input from a user and echoes that input back is potentially vulnerable. For example, a login page that prompts for a user name and password and then displays "Welcome back, <username>" on a successful login may be susceptible to an XSS attack.

Message boards, forums, and wikis are also often vulnerable to application security issues. In these sites, legitimate users post their thoughts or opinions, which are then visible to all other visitors to the site. But an attacker, rather than posting about the current topic, will instead post a message such as "<script>alert(document.cookie);</script>". The message board now includes the attacker's script code in its page code-and the browser then interprets and executes it for future site visitors. Usually attackers use such script code to try to obtain the user's authentication token (usually stored in a cookie), which they could then use to impersonate the user. When cookies are marked with the "HttpOnly" property, their values are hidden from the client, so this attack will fail.

As mentioned earlier, it is possible to enable "HttpOnly" programmatically on any individual cookie by setting the "HttpOnly" property of the "HttpCookie" object to "true." However, it is easier and more reliable to configure the application to automatically enable "HttpOnly" for all cookies. To do this, set the "httpOnlyCookies" attribute of the <httpCookies> element to "true."

5. Cookieless Session State Enabled


In the initial 1.0 release of ASP.NET, you had no choice about how to transmit the session token between requests when your Web application needed to maintain session state: it was always stored in a cookie. Unfortunately, this meant that users who would not accept cookies could not use your application. So, in ASP.NET 1.1, Microsoft added support for cookieless session tokens via use of the "cookieless" setting.

Vulnerable configuration:

<configuration>

<system.web>

<sessionState cookieless="UseUri">

Secure configuration:

<configuration>

<system.web>

<sessionState cookieless="UseCookies">

Web applications configured to use cookieless session state now stored the session token in the page URLs rather than a cookie. For example, the page URL might change from http://myserver/MyApplication/default.aspx to http://myserver/MyApplication/(123456789ABCDEFG)/default.aspx. In this case, "123456789ABCDEFG" represents the current user's session token. A different user browsing the site at the same time would receive a completely different session token, resulting in a different URL, such as http://myserver/MyApplication/(ZYXWVU987654321)/default.aspx.

While adding support for cookieless session state did improve the usability of ASP.NET Web applications for users who would not accept cookies, it also had the side effect of making those applications much more vulnerable to session hijacking attacks. Session hijacking is basically a form of identity theft wherein a hacker impersonates a legitimate user by stealing his session token. When the session token is transmitted in a cookie, and the request is made on a secure channel (that is, it uses SSL), the token is secure. However, when the session token is included as part of the URL, it is much easier for a hacker to find and steal it. By using a network monitoring tool (also known as a "sniffer") or by obtaining a recent request log, hijacking the user's session becomes a simple matter of browsing to the URL containing the stolen unique session token. The Web application has no way of knowing that this new request with session token "123456789ABCDEFG" is not coming from the original, legitimate user. It happily loads the corresponding session state and returns the response back to the hacker, who has now effectively impersonated the user.

The most effective way to prevent these session hijacking attacks is to force your Web application to use cookies to store the session token. This is accomplished by setting the "cookieless" attribute of the <sessionState> element to "UseCookies" or "false." But what about the users who do not accept cookies? Do you have to choose between making your application available to all users versus ensuring that it operates securely for all users? A compromise between the two is possible in ASP.NET 2.0. By setting the "cookieless" attribute to "AutoDetect," the application will store the session token in a cookie for users who accept them and in the URL for those who won't. This means that only the users who use cookieless tokens will still be vulnerable to session hijacking. That's often acceptable, given the alternative-that users who deny cookies wouldn't be able to use the application at all. It is ironic that many users disable cookies because of privacy concerns when doing so can actually make them more prone to attack.

Intermission

These first five Web.config vulnerabilities that we've discussed in this article have been applicable to all ASP.NET Web applications regardless of their methods of authentication, or even whether they use authentication at all. Part two of this article details an additional five vulnerabilities that apply only to applications using Forms authentication. These misconfigurations can be even more dangerous than the first five, giving intruders the ability to access supposedly secure areas of your Web site. Finally, we will also discuss some methods of locking down your configuration files so that they can't be modified unintentionally.

January 29, 2007

New HTTP Endpoints Create SQL Server 2005 Web Services

Aquí vengo de nuevo ahora con un artículo interesante. Habla de los EndPoints en SQL Server 2005

¿que es esto?, bueno pues es el manejo que se puede dar a los Web Services directamente desde SQL Server 2005
vale la pena implementar algo así.


Saludos y hasta la próxima!



Fuente: http://www.developer.com/db/article.php/10920_3390241_1


New HTTP Endpoints Create SQL Server 2005 Web Services
By Peter DeBetta

Go to page: 1 2 3 Next

by Peter DeBetta of Wintellect

SQL Server 2000 offers some capabilities for returning XML output via HTTP using SQLXML—and, of course, SQLXML supports Web services creation. Although not rocket science, setting up, configuring, and using Web services in SQL Server 2000 does require a little effort (see the SQLXML documentation about Web services in SQL Server 2000).

When .NET came about, people began writing Web services in C# or VB.NET. They simply connected into SQL Server (or any data store, for that matter) to retrieve the data. .NET made creating Web services as simple as 1-2-3:

  1. Create some stored procedures.
  2. Write some WebMethods to return the data from said stored procedures.
  3. Presto! You have a Web service.

But now, the next generation of Web services is hitting the streets. SQL Server 2005 supports native HTTP SOAP via a feature known as HTTP Endpoints. For those who don't know, Simple Object Access Protocol (affectionately known as SOAP) is a lightweight messaging protocol that Webopedia defines as follows:

"Short for Simple Object Access Protocol, a lightweight XML-based messaging protocol used to encode the information in Web service request and response messages before sending them over a network. SOAP messages are independent of any operating system or protocol and may be transported using a variety of Internet protocols, including SMTP, MIME, and HTTP ."

This new HTTP Endpoints feature in SQL Server 2005 is the subject of this article.

HTTP Endpoints

So what is an HTTP Endpoint? You may have heard that it is SQL Server 2005's means for creating Web services, but it actually is much more. An HTTP Endpoint also is a means of creating interfaces via HTTP or TCP for SOAP, T?SQL, Service Broker, and even database mirroring. Although these other functions are very intriguing, this discussion concerns only the ability to create Web services in SQL Server—Web services that can return rowset data, scalar values, messages, and even errors, all of which are serialized into XML automatically. And, an HTTP Endpoint does all of this without requiring you to install IIS (it uses the Windows 2003 kernel module http.sys).

Because I like to learn from examples, I am going to teach by example. I demonstrate how to use HTTP Endpoints by walking through an example from start to finish. Before starting, here are a few notes to consider:

  • This demonstration uses the new demo database called AdventureWorks.
  • Native HTTP SOAP in SQL Server 2005 is not supported on Windows XP. If you want to try the examples, you need Windows Server 2003.
  • SQL Server 2005 Express Edition (the new MSDE) does not support HTTP Endpoints, so be sure to install the Developer Edition.
  • I do not explain how to use SQL Server Management Studio to execute SQL scripts. I trust you know how to do this.

Security

Because HTTP Endpoints are a server-level feature, security of endpoints is also on the server level. Of course, the serveradmin system role can create, alter, and drop endpoints from the SQL Server instance, but how do you allow developers to manage these endpoints without giving them the excessive permissions of this system role?

The answer lies in SQL Server 2005's new ability to assign server-level permissions to logins, as shown here:

GRANT ALTER ANY HTTP ENDPOINT TO peter

With this command, you can allow the peter login to manage HTTP Endpoints without giving other unnecessary permissions. The following is a list of permissions that you can modify via GRANT, DENY, or REVOKE:

  • {GRANT|DENY|REVOKE} ALTER ANY ENDPOINT TO Login
    Controls the ability to alter any HTTP Endpoint; also allows permission to transfer ownership and connect to any endpoint
  • {GRANT|DENY|REVOKE} ALTER ON ENDPOINT:: EndPointName TO Login
    Controls whether a login can alter a specific HTTP Endpoint; also allows permission to transfer ownership and connect to the specified endpoint
  • {GRANT|DENY|REVOKE} CONTROL ON ENDPOINT:: EndPointName TO Login
    Controls whether a login can alter or drop a specific HTTP Endpoint; also allows permission to transfer ownership and connect to the specified endpoint
  • {GRANT|DENY|REVOKE} CONNECT ON ENDPOINT:: EndPointName TO Login
    Controls whether or not a login can connect to (execute requests against) an HTTP Endpoint
  • {GRANT|DENY|REVOKE} TAKE OWNERSHIP ON ENDPOINT:: EndPointName
    TO Login
    Controls whether a login can take ownership of the HTTP Endpoint
  • {GRANT|DENY|REVOKE} VIEW DEFINITION ON ENDPOINT:: EndPointName
    TO Login
    Controls the ability for a login to see the metadata (definition) of the HTTP Endpoint

Consider one last example. If I want to deny the peter login the ability to use an HTTP Endpoint named SQLEP_Financial, I would execute the following statement:

DENY CONNECT ON ENDPOINT::SQLEP_Financial TO peter

Providing a Source for Data

The first order of business is to create the code components that will be the source of information for the endpoint. I create two stored procedures and one user-defined function (UDF), as shown in Listing 1:

Listing 1

USE AdventureWorks
GO
CREATE PROCEDURE prProductList
AS
SELECT Product.ProductID, Product.ProductNumber, Product.Name
FROM Production.Product AS Product
INNER JOIN Production.ProductInventory AS Inventory
ON Product.ProductID = Inventory.ProductID
INNER JOIN Production.Location AS Location
ON Inventory.LocationID = Location.LocationID
WHERE Product.ListPrice > 0
AND Location.LocationID = 6 --Products from Misc Storage only
ORDER BY Product.Name
GO
CREATE PROCEDURE prProductStockInfo
@ProductID int
AS
IF (SELECT ListPrice FROM Production.Product
WHERE ProductID = @ProductID) = 0
BEGIN
RAISERROR ('Product not available for retail sale', 11, 1)
END
ELSE
BEGIN
SELECT Product.ProductID , Product.ProductNumber,
Product.Name, Product.Weight,
Product.WeightUnitMeasureCode,
Product.ListPrice, Inventory.Quantity
FROM Production.Product AS Product
INNER JOIN Production.ProductInventory AS Inventory
ON Product.ProductID = Inventory.ProductID
INNER JOIN Production.Location AS Location
ON Inventory.LocationID = Location.LocationID
WHERE Product.ProductID = @ProductID
AND Location.LocationID = 6 --Misc Storage
END
GO
CREATE FUNCTION dbo.fnProductPhoto (@ProductID int)
RETURNS varbinary(MAX)
AS
BEGIN
DECLARE @largePhoto varbinary(max)

SELECT @largePhoto = ProdPhoto.LargePhoto
FROM Production.ProductPhoto AS ProdPhoto
INNER JOIN Production.ProductProductPhoto ProdProdPhoto
ON ProdPhoto.ProductPhotoID = ProdProdPhoto.ProductPhotoID
WHERE ProdProdPhoto.ProductID = @ProductID

RETURN (@largePhoto)
END

The first procedure returns a list of products (product ID, name, and number) from the AdventureWorks database. The second procedure returns more details about a product, including inventory levels. The UDF returns a single varbinary value containing the product photo.

Creating the Endpoint

Once you have your procedures and functions set up, you can create the endpoint (Web service). The following code creates the endpoint on my server:

CREATE ENDPOINT SQLEP_AWProducts
STATE = STARTED
AS HTTP
(
PATH = '/AWproducts',
AUTHENTICATION = (INTEGRATED),
PORTS = (CLEAR),
SITE = 'win2k301'
)
FOR SOAP
(
WEBMETHOD 'ProductList'
(NAME='AdventureWorks.dbo.prProductList'),
WEBMETHOD 'ProductStockInfo'
(NAME=' AdventureWorks.dbo.prProductStockInfo'),
WEBMETHOD 'ProductPhoto'
(NAME='AdventureWorks.dbo.fnProductPhoto'),
BATCHES = DISABLED,
WSDL = DEFAULT,
DATABASE = 'AdventureWorks',
NAMESPACE = 'http://Adventure-Works/Products'
)

Believe it or not, you are now ready to consume this Web service. Before doing that, though, examine the CREATE ENDPOINT statement. Starting from the top, the first thing you will notice is the name of the endpoint, SQLEP_AWProducts, which is how you refer to the Web service within your client code (see Figure 1). PATH is the virtual path on the server for the Web service. So, for this example, you would access the Web service at http://win2k301/AWproducts, but it would be called SQLEP_AWProducts in your .NET application code. Table 1 provides explanations for this and other arguments used in the AS HTTP clause.



Click here for a larger image.

Figure 1: Object Browsing the Web Service in Visual Studio.NET 2005

Table 1: Arguments Used in the AS HTTP Clause

Argument Description
PATH The virtual URL path on the server where the Web service will reside
AUTHENTICATION

The method of authentication; can be BASIC, DIGEST, or INTEGRATED

You should try to use INTEGRATED when possible, since it is the most secure. It will try to use Kerberos-based authentication if possible (otherwise, NTLM).

DIGEST is not as secure as INTEGRATED. You should use it only if INTEGRATED authentication is not possible.

BASIC authentication is the least secure. You should use it only if you can't implement either INTEGRATED or DIGEST authentication methods. BASIC requires SSL (see PORTS below).

PORTS CLEAR (HTTP - port 80 by default) SSL (HTTPS - port 443 by default)
SITE The name of the server on which the Web service is running

The STATE argument can have one of three values:

  • STARTED—listening and responding
  • DISABLED—neither listening nor responding
  • STOPPED—listening, but returns errors to client requests

You can change the state of an existing Web service using the ALTER ENDPOINT statement. For example, to disable the endpoint, you can execute:

ALTER ENDPOINT SQLEP_AWProducts STATE = DISABLED

The FOR SOAP clause determines which methods the Web service will expose, which other features are exposed (dynamic SQL, for example), and other characteristics of the Web service. In this example, three methods are exposed: the two stored procedures and the UDF shown in Listing 1. WEBMETHOD requires the name of the exposed method as its first argument. As you can see in the code, it does not have to match the name of the actual stored procedure or UDF that it is exposing. The next argument of WEBMETHOD is the fully qualified NAME of the object you are exposing.

The BATCHES argument specifies whether or not the Web service supports ad hoc queries. WSDL indicates how the WSDL document generation will occur; DEFAULT indicates that the WSDL document will be created automatically. SQL Server 2005 allows you to implement custom WSDL generators using the CLR-based abilities of SQL Server 2005 (see Books Online for more details). DATABASE is the name of the database that will be accessed from the endpoint (endpoints are defined at the server level). And finally, NAMESPACE is, well, the namespace for the endpoint.

You have now officially created a Web service using SQL Server 2005. Congratulations.



The Client to Consume Your Web Service

Consuming a Web service created in SQL Server 2005 as an HTTP Endpoint is similar to consuming a Web service created in C#. That's the beauty of Web services and SOAP. Begin a new Windows application in Visual Studio.NET and add the following controls to the form (ControlType: name):

  • Button: btnExecSP
  • DataGridView: dgvProduct
  • ListBox: lstProducts
  • PictureBox: picProduct

You will need to add the Web reference before writing any code. Again, you can browse to http://server/awproducts?wsdl to create the Web reference. Keep in mind that your Web reference object will be named server_AWProducts (my machine is named win2k301 so I browse to http://win2k301/awproducts?wsdl, and my Web reference object is win2k301_AWProducts). You will have to tweak the code to the Web reference name that you create.

Once the Web reference is in place, you can double-click the Button control and add the code in Listing 2.

Listing 2

private void BtnExecSP_Click(System.Object sender, System.EventArgs e)
{
win2k301_AWProducts.SQLEP_AWProducts proxy =
new win2k301_AWProducts.SQLEP_AWProducts();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials ;

object[] products = proxy.ProductList();
System.Data.DataSet resultDS;

if (products[0].ToString() == "System.Data.DataSet")
{
resultDS = (System.Data.DataSet )products[0];
DataTable dt = resultDS.Tables[0];
lstProducts.DataSource = dt;
lstProducts.DisplayMember = "Name";
lstProducts.ValueMember = "ProductID";
}
}

The first thing you will notice is that the Web method returns an object array. Because SQL Server can actually send back not only result sets, but also messages, errors, and other types (see Table 2 for more details), you should validate that you received what you expected. Listing 2 does a check by using the ToString method on the first element in the returned object array and comparing it to "System.Data.DataSet". If true, you know you can safely cast the object to a DataSet type and work with it from there.

Table 2: Object Return Types

Item from SQL Server Corresponding .NET Object
Results of SELECT statement System.Data.DataSet
Results of a SELECT statement with FOR XML System.Xml.XmlElement
Raised error SqlMessage (from WSDL)
Message SqlMessage (from WSDL)
Output parameter SqlParameter (from WSDL)
Rows affected SqlRowCount (from WSDL)
RETURN statement value System.Int32

Now double-click the ListBox control and add the following code:

private void lstProducts_SelectedIndexChanged(object sender,
System.EventArgs e)
{
Int32 i = 0;
try
{i = System.Convert.ToInt32(lstProducts.SelectedValue.ToString ());}
catch
{return;} //prevents issue when loading listbox

object e1;
win2k301_AWProducts.SqlMessage errorMessage;
System.Data.DataSet resultDS;

win2k301_AWProducts.SQLEP_AWProducts proxy =
new win2k301_AWProducts.SQLEP_AWProducts();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

object[] products = proxy.ProductStockInfo(i);
e1 = products[0];
switch ( e1.ToString())
{
case "System.Data.DataSet":
resultDS = (System.Data.DataSet)products[0];
DataTable dt = resultDS.Tables[0];
dgvProduct.DataSource = dt;
dgvProduct.Refresh();
break;
case "Yukon_Http_v1.win2k301_AWProducts.SqlMessage":
errorMessage = (win2k301_AWProducts.SqlMessage)products[0];
MessageBox.Show("Error fetching product", "'"
+ errorMessage.Message + " occurred at '"
+ errorMessage.Source + "'");
return;
}
Byte[] photo = proxy.ProductPhoto(i);
picProduct.Image = new Bitmap(new MemoryStream(photo));
}

You should pay attention to a couple of details here. First, this code snippet checks for another type of returned object: SqlMessage. Notice the type name (from the ToString method) is Yukon_Http_v1.server_virtualDirectory.SqlMessage. This type is defined in the WSDL document and is unique to each Web service. The following listing shows a snippet from the WSDL of the SqlMessage complexType:

<xsd:complexType name="SqlMessage">
<xsd:sequence minOccurs="1" maxOccurs="1">
<xsd:element name="Class" type="sqlmessage:nonNegativeInteger" />
<xsd:element name="LineNumber"
type="sqlmessage:nonNegativeInteger" />
<xsd:element name="Message" type="xsd:string" />
<xsd:element name="Number" type="sqlmessage:nonNegativeInteger" />
<xsd:element name="Procedure" type="xsd:string" minOccurs="0" />
<xsd:element name="Server" type="xsd:string" minOccurs="0" />
<xsd:element name="Source" type="xsd:string" />
<xsd:element name="State" type="sqlmessage:nonNegativeInteger" />
</xsd:sequence>
</xsd:complexType>

The last tidbit for this discussion is the Byte array that is returned from the UDF. Because this UDF returned varbinary data, its XSD type is xsd:base64Binary. Thus, it is a Byte array in .NET. SQL Server's int data type is the XSD type xsd:int and Int32 in .NET. Books Online has more information about the mapping of types.

Easy Web Service Creation

HTTP Endpoints provide a way to create various interfaces into SQL Server, including features such as Service Broker, database mirroring, and of course, Web services. It makes the creation of a Web service (that exposes SQL Server data) a snap for experienced programmers and database administrators alike. Enjoy!

About the Author

Peter DeBetta is an independent software consultant who trains exclusively for Wintellect. Peter regularly publishes on the topic of SQL Server and recently wrote Introducing SQL Server 2005 for Developers for Microsoft Press. He also speaks at conferences such as VSLive!, WinSummit, WinDev, and Devscovery.

August 27, 2006

Microsoft Office Open XML Formats

Leyendo por ahi una artículo en la pagina de MS, encontre un video que no muestra el manejo de los nuevos documentos de Office 2007 en VS 2005.

Por default, los documentos creados en la nueva versión de MS Office estarán basados en el nuevo formato XML para archivos. A diferencia de los documentos binarios de las anteriores versiones de Office, los nuevos formatos XML de Office son compactos, robustos y facilitan una mejor integración entre los documentos y los sistemas back-end. Esta especificación abrierta y libre maximiza la interoperatividad en ambientes eterogeneos, y facilita la integración de los documentos office con las tecnologías de terceros.

Los nuevos formatos XML de Office introduce un nuemero de beneficios no solo para los desarrolladores y las soluciones que estos construyen, sino también para los usuarios individuales y para las organizaciones.


Para encontrar más información ve a : http://www.microsoft.com/office/preview/itpro/fileoverview.mspx

Aquí les dejo un video que muestra el manejo de los documentos de Office 2007 en VS 2005. Les rescomiendo
que lo vena en el tamaño original, se aprecia mucho mejor, aqui esta el link directo al video

Espero nos sirva de algo.





Si no puedes ver el video.. usa Firefox :P, o da click aqui

June 2, 2006

.Net : Crear un archivo de Excel, Parte 2

Esta es la segunda parte de la creación de un archivo de Excel. En esta entrega veremos
todo el código necesario para crear la forma en donde visualizaremos los datos de la tabla,
y posteriormente llenar una hoja de un archivo de excel con esa información

El ultimo paso es el guardar el archivo con un nombre.

En esta entrega estamos haciendo un barrido de filas y columnas para llenar el archivo de excel,
en la siguiente parte daremos una explicación de un método distinto de llenado, presentando
así sus pros y contras.



Imports System.Data.SqlClient
Imports Excel


Public Class frmCreateExcelfile
Inherits System.Windows.Forms.Form

Private ds As DataSet
Private objExcel As Excel.Application
Private objWBook As Excel._Workbook
Private objWSheet As Excel._Worksheet
Private objRange As Excel.Range

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
DisposeExcelObjects()
Me.Close()
End Sub

Private Sub DisposeExcelObjects()
Try
objWBook.Close()
objExcel.Workbooks.Close()
Catch ex As Exception

End Try

objExcel.Quit()
If Not objRange Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRange)
End If
If Not objExcel Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel)
End If
If Not objWBook Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(objWBook)
End If
If Not objWSheet Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(objWSheet)
End If

objWBook = Nothing
objWSheet = Nothing
objExcel = Nothing
GC.Collect()

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cnx As System.Data.SqlClient.SqlConnection
Dim da As System.Data.SqlClient.SqlDataAdapter
Dim cm As System.Data.SqlClient.SqlCommand

Try
cnx = New System.Data.SqlClient.SqlConnection("Data Source=XXX.XXX.XXX.XXX;User Id=XXX;Password=XXX;Initial Catalog=Northwind")

cm = New System.Data.SqlClient.SqlCommand
cm.CommandType = CommandType.Text
cm.CommandText = "SELECT * FROM Employees ORDER BY LastName"
cm.Connection = cnx

da = New System.Data.SqlClient.SqlDataAdapter(cm)

ds = New DataSet
da.Fill(ds)

DataGrid1.DataSource = ds.Tables(0)

Catch ex As Exception
MsgBox(ex.ToString)
Finally
cnx.Close()
cm.Dispose()
cnx.Dispose()
cnx = Nothing
End Try
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
objExcel = New Excel.Application
objExcel.ScreenUpdating = False
objExcel.Visible = False


objWBook = objExcel.Workbooks.Add()

objWSheet = CType(objWBook.Sheets.Item(1), Excel._Worksheet)

Fillsheet(ds)
End Sub

Private Sub Fillsheet(ByVal ds As DataSet)
Dim arrData() As Object
Dim dr As DataRow
Dim i As Int32
Dim j As Int32

ReDim arrData(ds.Tables(0).Columns.Count)

'objWSheet = CType(objWBook.Sheets.Item("Sheet1"), Excel._Worksheet)
objWSheet.Activate()


For i = 0 To ds.Tables(0).Rows.Count - 1
dr = ds.Tables(0).Rows(i)

For j = 0 To 13
'arrData(j) = IIf(IsNumeric(dr(j).ToString), dr(j), dr(j).ToString)
objWSheet.Cells.Item(i + 1, j + 1) = dr(j)
Next
Next


objWSheet.SaveAs(TextBox1.Text)

End Sub
End Class


Esta es una imagen del archivo generado:

June 1, 2006

.Net : Crear un archivo de Excel, Parte 1

En esta ocación crearemos un archivo de Excel a través de .Net. El alcance de este post es la
creación en si del archivo y el llenado simple con la información de una tabla.

Private ds As DataSet
Private objExcel As Excel.Application
Private objWBook As Excel._Workbook

Private objWSheet As Excel._Worksheet
Private objRange As Excel.Range

objExcel = New Excel.Application
objExcel.ScreenUpdating = False
objExcel.Visible = False

objWSheet = CType(objWBook.Sheets.Item(sheetName), Excel._Worksheet)
objWSheet.Activate()

objWSheet.Cells.Item(1, 1) = "Metxtli" ' Escribir en "A1"


objWBook.Close()
objExcel.Workbooks.Close()


En pocas lineas estos son los pasos para crear un archivo de excel, voy
un ejemplo completo en una forma de windows.



La idea es a partir de la información contenida en el DataGrid crear
un archivo de excel con toda esta información.