ERROR: “Could not allocate space for object ‘X’ in database ‘Your Database’ because the ‘PRIMARY’ filegroup is full”

“Could not allocate space for object ‘X’ in database ‘Your Database’ because the ‘PRIMARY’ filegroup is full” error Issue

You receive an error similar to: ‘Could not allocate space for object ‘X’ in dabase ‘Your Database’ because the ‘PRIMARY’ filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting auto growth on for existing files in the filegroup.’ when browsing to your site.

Cause
Your database is either too big or had an artificial size limitation imposed on it by a previous host.

Resolution
The following steps require Microsoft SQL Server Management Studio. If you do not have this installed on your local computer please follow the instructions at How To Connect to Your MS SQL 2008 Database and Disable Collation

  1. Open Microsoft SQL Server Management Studio.
  2. Right click [your database] and select Properties.
  3. In the left navigation window of the dialog box that pops up, select Files.
  4. In the Autogrowth column select the button noted in the image below and change them it to Unrestricted Growth under Maximum File Size.
    Change Autogrowth MS SQL Settings
  5. Repeat step 4 for the second file type.
  6. Click OK
  7. Reset your site (reset the web.config file by renaming the files and saving it, then renaming it back.)

If you still continue to get this error, your database is over 4 GB in size.  You can shrink your database using the instructions at How To Truncate Your DNN Logs In Your MSSQL Database then follow the above resolution again.

via: https://support.managed.com/kb/a132/error-could-not-allocate-space-object-x-database-your-database-because-primary-filegroup-is-full.aspx

Qué es el stack MEAN y cómo escoger el mejor para ti

Últimamente está muy de moda algo llamado MEAN o más concretamente del “Stack MEAN” para desarrollo web basado en JavaScript, del que seguramente habrás oído hablar.

Como ya he comentado en otras ocasiones, el lenguaje JavaScript se está haciendo un hueco cada vez mayor en el mercado del desarrollo de software. Aquel humilde lenguaje que empezó en los años ’90 como una vía sencilla de validar formularios, se ha convertido en parte fundamental del desarrollo de todo tipo de aplicaciones: web, móviles, bases de datos, administración de sistemas…

Esta proliferación ha llevado a JavaScript a todas las capas de desarrollo, empezando por el lado cliente en sus inicios (el navegador), pero yendo también al servidor y a la capa de almacenamiento. En cualquiera de esos puntos podemos encontrar JavaScript listo para ser utilizado.

Gracias a eso, hoy en día es posible crear aplicaciones distribuidas utilizando el mismo lenguaje JavaScript en todas sus fases y capas. A este concepto y las tecnologías que lo posibilitan se les ha bautizado con el nombre de MEAN, acrónimo formado por las iniciales de las cuatro tecnologías principales que entran en juego: MongoDB, Express, AngularJS y Node.js.

MEAN_750

En mi opinión, por orden lógico, debería llamarse ANEM o incluso MENA, pero la verdad es que MEAN queda mejor y le da un toque agresivo (“mean” en inglés de la calle significa, entre otras cosas, borde, desconsiderado, incluso malévolo, aunque también es sinónimo de “cool”). AMEN tampoco hubiera estado mal 🙂

Veamos cada una de sus partes principales

Node.js

imageEsto no lo sabe todo el mundo pero, de hecho, JavaScript nació en el lado servidor casi al mismo tiempo que en el navegador. La propia empresa que creó el lenguaje, Netscape, lo incluyó también en su servidor webllamado Netscape Enterprise Server, aunque con poco éxito. Poco despuésMicrosoft lo incorporó a su ASP clásico, donde todavía funciona (aunque los programadores se decantaron más por el lenguaje VBScript). Muchos otros han hecho lo mismo.

No es sin embargo hasta hace relativamente poco, en 2009, cuando un proyecto empezó a poner en el mapa realmente a JavaScript en el lado servidor. Se trata de Node.js, un entorno de ejecución de aplicaciones multiplataforma y de código abierto (Open Source).

Node.js utiliza por debajo el motor de JavaScript de Google, denominado V8, y provee de una arquitectura orientada a eventos (como la de los navegadores) así como una serie de APIs no-bloqueantes (asíncronas) que le proporcionan un rendimiento y una escalabilidad muy elevadas. Se puede utilizar para crear cualquier tipo de lógica de aplicación, pero dado que incorpora un módulo para poder actuar como un servidor web, es especialmente popular para crear aplicaciones web. Actualmente lo emplean para sus aplicaciones multitud de empresas de todos los ámbitos pero especialmente de Internet: PayPal, SAP, Groupon… incluso la mismísima Microsoft, que ayuda a crear la versión para Windows (bajo IIS funciona de maravilla, con grandes ventajas frente a hostearlo solo) y lo soporta en Azure y en sus herramientas de desarrollo.

Gracias a Node.js se pueden crear gratuitamente aplicaciones web de alto rendimiento, en cualquier sistema operativo y utilizando como único lenguaje de programación JavaScript.

Express

imageNode.js por sí mismo está muy bien para crear la lógica de las aplicaciones, y como dispone de un módulo para el protocolo HTTP es posible crear aplicaciones web con lo que trae por defecto. Sin embargo es complejo, costoso y tenemos que hacer todo el trabajo a bajo nivel nosotros mismos.

Para ayudar a crear aplicaciones web más fácilmente nació Express. Este framework está escrito en JavaScript para Node.js. Su objetivo es que no tengamos que reinventar la rueda cada vez que queramos crear una aplicación web, ofreciéndonos soporte para las principales necesidades en este tipo de aplicaciones: gestión de peticiones y respuestas, cabeceras, rutas, vistas…

Digamos que Node.js sin Express.js sería mucho menos de lo que es hoy. Y costaría 10 veces más construir aplicaciones web con JavaScript. Así que van unidos felizmente en el servidor para permitirnos crear aplicaciones web de manera sencilla, por eso los he puesto juntos en la capa del medio de la figura anterior.

AngularJS

imageAunque evidentemente en el navegador podríamos desarrollar todo el código usando solamente HTML, CSS y JavaScript puro, qué duda cabe que disponer de alguna biblioteca que nos proporcione muchas funcionalidades ya hechas, facilita mucho las cosas. Es algo parecido a lo que pasa con Node.js y Express.js: el primero puede funcionar sin el segundo, pero seríamos tontos si no utilizásemos este último.

En el navegador desde siempre han existido bibliotecas de funciones que nos facilitan mucho la vida. La más conocida y utilizada es sin duda jQuery, que también fue una de las primeras en ser adoptada universalmente. En los últimos años se ha trasladado al navegador el patrón de diseño denominado MVC (Modelo-Vista-Controlador) y han surgido cientos de bibliotecas especializadas en facilitarnos su uso. De entre todas ellas destaca AngularJS que ha tomado un especial protagonismo en los últimos tiempos, entre otras muchas cosas porque está creada y soportada por Google, es gratuita y de código abierto.

Algunos han definido a AngularJS como “lo que HTML debería haber sido si se hubiese diseñado para crear aplicaciones”. Ahí queda eso.

Angular.js va mucho más allá de ser una simple biblioteca de funciones: es un completo framework que nos brinda todo tipo de funcionalidades avanzadas, extendiendo de hecho HTML.

MongoDB

imageEn el lado del almacenamiento se han utilizado tradicionalmente bases de datos relacionales. Sin embargo, actualmente, los tipos de información que suelen requerir las aplicaciones web demandan mayor flexibilidad, menos coherencia y sobre todo mayor capacidad de escalar. Para dar respuesta a todo esto surge la tendencia tecnológica en almacenes de datos que se denomina NoSQL.

Estos almacenes de datos NoSQL pueden ser de diversos tipos, pero en muchos casos utilizan JavaScript para representar la información, recibiendo, enviando y almacenando datos usando la notación JSON (ver más abajo).

De entre todos estos almacenes de datos no-relacionales hay uno que destaca especialmente: MongoDB, y que es la “M” del stack MEAN.

No voy a entrar más detalles aquí porque ya he escrito mucho anteriormente sobre este tema. Así que si necesitas aprender lo fundamental sobre la tecnología NoSQL, sus motivaciones, sus limitaciones, sus aplicaciones… y también sobre MongoDB, léete el artículo “Fundamentos de bases de datos NoSQL: MongoDB“, donde te lo explico todo.

JSON

imageEsto no forma parte del acrónimo MEAN, pero es una parte integral del mismo. Es también a su vez una palabra formada por iniciales de palabras, y significa:JavaScript Simple Object Notation.

Como su propio nombre indica JSON (pronunciado “yeison”) permite representar objetos (en realidad estructuras complejas) en forma de código JavaScript que luego podemos evaluar. Su padre es Douglas Crockford.

Este formato es ligero, fácilmente legible por un humano pero también por un ordenador, está basado en JavaScript y además es muy fácil de procesar por parte de cualquier intérprete de este lenguaje.

Por ejemplo, este es un objeto JSON que representa un contacto:

{
 "nombre" : "José Manuel",
 "apellidos" : "Alarcón Aguín",
 "empresa" : "campusMVP",
 "telefono" : "986 165 802",
 "edad" : 42
}

Como vemos no es más que un objeto JavaScript normal y corriente. Crearlo es muy fácil pues es sintaxis JavaScript convencional. Enwww.json.org es posible encontrar una explicación completa de esta notación.

JSON es el pegamento de todas las capas. Es el formato en el que se transfieren los datos entre todos los niveles de la aplicación: navegador, servidor web y servidor de datos.

Aunque no forme parte del nombre es una parte esencial del stack MEAN.

Otros elementos

Con estas piezas ya tenemos lo fundamental del stack MEAN, aunque por supuesto necesitamos HTML y CSS, y muchas otras pequeñas piezas para facilitarnos el trabajo. Por ejemplo:

  • Es muy común usar Require.jsBrowserify para definir y cargar módulos asíncronamente en nuestras aplicaciones, ganando en agilidad de carga de las aplicaciones y evitando problemas de dependencias.
  • También existen infinidad de bibliotecas especializadas en todo tipo de cuestiones, como el manejo de fechas, la creación de plantillas y enlazado a datos, gráficas, etc, etc, etc…
  • Herramientas de testeo de aplicaciones, como QUnit, jasmine o Selenium.
  • Metalenguajes: lenguajes encima de otros lenguajes que ayudan a ser más eficiente y trabajar más fácilmente. Por ejemplo, con Sass o Less podemos escribir hojas de estilo mucho más potentes, flexibles y con más facilidad que con CSS. Estos lenguajes compilan luego a CSS estándar. Lo mismo ocurre con JavaScript. Metalenguajes como CoffeeScript o TypeScript ofrecen capacidades que no tiene JavaScript nativamente pero luego compilan a JavaScript nativo. De este modo podemos trabajar de manera mucho más eficiente con características más avanzadas en el lenguaje, pero obteniendo al final JavaScript puro.

Para poner orden en todo esto herramientas como Bower, un gestor de paquetes para desarrollo web en lado cliente, o Yeoman, capaz de generar y darnos ya hecha la base de muchas aplicaciones usando todo tipo de bibliotecas.

Y salvo que uses Visual Studio, WebStorm o herramientas avanzadas similares, lo más normal es que necesites automatizar muchas tareas antes de desplegar tu aplicación: conversión de SaaS o Less a CSS, de CoffeScript o TypeScript a JavaScript, minimización y ofuscación de código, ejecución de pruebas…. Para facilitarnos esto existen herramientas basadas en JavaScript como Grunt.

Herramientas_FrontEnd

No se vayan todavía… aún hay más…

Por si todo esto no fuera suficiente, todavía hay algo más para acabar de complicarlo.

Una vez que tenemos claro qué es el stack MEAN y qué componentes lo conforman, si se nos ocurre buscar información en la Web sobre “stack MEAN” veremos que nos aparecen muchos proyectos que dicen ser la base de dicho stack. Los dos más populares y que seguro que nos topamos enseguida son Mean.js y Mean.io.

Ambos afirman ser una solución completa de código abierto para el stack MEAN y que abarcan el stack completo. WTF?

Esto lo que significa es que ambos nos proporcionan una base de la que partir para construir aplicaciones basadas en MEAN, de forma que tengamos parte del camino andado. Ambos son muy parecidos (de hecho parten de la misma base pues Mean.js es un fork de Mean.io, que empezó antes) pero tienen filosofías diferentes a la hora de construir las aplicaciones.

¿Cuál elegir? Bueno, difícil responder, pues ambos son excelentes. Por un lado Mean.js está mejor documentado que Mean.io, pero sin embargo este último tiene una comunidad más activa por lo que nos será más fácil conseguir ayuda…

Por otro lado, lo sorprendente es que ambos fueron creados por el mismo desarrollador Amos Haviv, que lo inició bajo los auspicios de una empresa que le daba soporte. Al cabo de un tiempo surgieron conflictos, así que abandonó el proyecto y ahora mantiene Mean.js (aquí lo explica él mismo). En ese sentido esta segunda opción puede parecer mejor, pues el creador original es por la que ha apostado, pero por otro lado Mean.io tiene detrás a una empresa que garantiza su soporte… Difícil elección.

Además de estos dos hay unos cuantos más, como por ejemplo:

Sea como sea, cualquiera de ellos es una buena elección. Es cuestión de acostumbrarse al modo de trabajar de cada uno y todos están bien documentados.

Además, siempre podemos partir totalmente de cero y trabajar como queramos con las piezas del puzle.

La elección es tuya.

via: http://www.campusmvp.es/recursos/post/Que-es-el-stack-MEAN-y-como-escoger-el-mejor-para-ti.aspx

GUIDs as PRIMARY KEYs and/or the clustering key

Expanding on the topic of “are you kidding me”… one of the MOST PREVALENT problems I see today is the dreaded “GUIDs as PKs” problem. However, just to be clear, it’s not [as much of a] problem that your PRIMARY KEY is a GUID as much as it is a problem that the PRIMARY KEY is probably your clustering key. They really are two things BUT the default behavior in SQL Server is that a PRIMARY KEY uses a UNIQUE CLUSTERED INDEX to enforce entity integrity. So, I thought I’d take this post to really dive into why this is a problem and how you can hope to minimize it.

Relational Concepts – What is a PRIMARY KEY? (quick and basic reminder for what is what and why)

Starting at the very beginning… a primary key is used to enforce entity integrity. Entity integrity is the very basic concept that every row is uniquely identifiable. This is especially important in a normalized database because you usually end up with many tables and a need to reference rows across those tables (i.e. relationships). Relational theory says that every table MUST have a primary key. SQL Server does not have this requirement. However, many features – like replication – often have a requirement on a primary key so that they can guarantee which row to modify on a related database/server (like the subscriber in a replication environment). So, most people think to create one. However, not always…

What happens when a column(s) is defined as a PRIMARY KEY – in SQL Server?

The first thing that SQL Server checks is that ALL of the columns that make up the PRIMARY KEY constraint do not all NULLs. This is a requirement of a PRIMARY KEY but not a requirement of a UNIQUE KEY. They also check to make sure (if the table has data) that the existing data meets the uniqueness requirement. If there are any duplicate rows, the addition of the constraint will fail. And, to check this as well as to enforce this for [future] new rows – SQL Server builds a UNIQUE index. More specifically, if you don’t specify index type when adding the constraint, SQL Server makes the index a UNIQUE CLUSTERED index. So, why is that interesting…

What is a clustered index?

In SQL Server 7.0 and higher the internal dependencies on the clustering key CHANGED. (Yes, it’s important to know that things CHANGED in 7.0… why? Because there are still some folks out there that don’t realize how RADICAL of a change occurred in the internals (wrt to the clustering key) in SQL Server 7.0). It’s always (in all releases of SQL Server) been true that the clustered index defines the order of the data in the table itself (yes, the data of the table becomes the leaf level of the clustered index) and, it’s always been a [potential] source of fragmentation. That’s really not new. Although it does seem like it’s more of a hot topic in recent releases but that may solely because there are more and more databases out there in general AND they’ve gotten bigger and bigger… and you feel the effects of fragmentation more when databases get really large.

What changed is that the clustering key gets used as the “lookup” value from the nonclustered indexes. Prior to SQL Server 7.0, SQL Server used a volatile RID structure. This was problematic because as records moved, ALL of the nonclustered indexes would need to get updated. Imagine a page that “splits” where half of the records are relocated to a new page. If that page has 20 rows then 10 rows have new RIDs – that means that 10 rows in EACH (and ALL) of your nonclustered indexes would need to get updated. The more nonclustered indexes you had, the worse it got (this is also where the idea that nonclustered indexes are TERRIBLY expensive comes from). In 7.0, the negative affects of record relocation were addressed in BOTH clustered tables and heaps. In heaps they chose to use forwarding pointers. The idea is that the row’s FIXED RID is defined at insert and even if the data for the row has to relocate because the row no longer fits on the original page – the rows RID does not change. Instead, SQL Server just uses a forwarding pointer to make one extra hop (never more) to get to the data. In a clustered table, SQL Server uses the clustering key to lookup the data. As a result, this puts some strain on the clustering key that was never there before. It should be narrow (otherwise it can make the nonclustered indexes UNNECESSARILY wide). The clustering key should be UNIQUE (otherwise the nonclustered indexes wouldn’t know “which” row to lookup – and, if the clustering key is not defined as unique then SQL Server will internally add a 4-byte uniquifier to each duplicate key value… this wastes time and space – both in the base table AND the nonclustered indexes). And, the clustering key should be STATIC (otherwise it will be costly to update because the clustering key is duplicated in ALL nonclustered indexes).

In summary, the clustering key really has all of these purposes:

  1. It defines the lookup value used by the nonclustered indexes (should be unique, narrow and static)
  2. It defines the table’s order (physically at creation and logically maintained through a linked list after that) – so we need to be careful of fragmentation
  3. It can be used to answer a query (either as a table scan – or, if the query wants a subset of data (a range query) and the clustering key supports that range, then yes, the clustering key can be used to reduce the cost of the scan (it can seek with a partial scan)

However, the first two are the two that I think about the most when I choose a clustering key. The third is just one that I *might* be able to leverage if my clustering key also happens to be good for that. So, some examples of GOOD clustering keys are:

  • An identity column
  • A composite key of date and identity – in that order (date, identity)
  • A pseudo sequential GUID (using the NEWSEQUENTIALID() function in SQL Server OR a “homegrown” function that builds sequential GUIDs – like Gert’s “built originally to use in SQL 2000” xp_GUID here:http://sqldev.net/xp/xpguid.htm

But, a GUID that is not sequential – like one that has it’s values generated in the client (using .NET) OR generated by the newid() function (in SQL Server) can be a horribly bad choiceprimarily because of the fragmentation that it creates in the base table but also because of its size. It’s unnecessarily wide (it’s 4 times wider than an int-based identity – which can give you 2 billion (really, 4 billion) unique rows). And, if you need more than 2 billion you can always go with a bigint (8-byte int) and get 263-1 rows. And, if you don’t really think that 12 bytes wider (or 8 bytes wider) is a big deal – estimate how much this costs on a bigger table and one with a few indexes…

  • Base Table with 1,000,000 rows (3.8MB vs. 15.26MB)
  • 6 nonclustered indexes (22.89MB vs. 91.55MB)

So, we’re looking at 25MB vs 106MB – and, just to be clear, this is JUST for 1 million rows and this is really JUST overhead. If you create an even wider clustering key (something horrible like LastName, FirstName, MiddlieInitial – which let’s say is 64bytes then you’re looking at 427.25MB *just* in overhead….. And, then think about how bad that gets with 10 million rows and 6 nonclustered indexes – yes, you’d be wasting over 4GB with a key like that.

And, fragmentation costs you even more in wasted space and time because of splitting. Paul’s covered A LOT about fragmentation on his blog so I’ll skip that discussion for now BUT if your clustering key is prone to fragmentation then you NEED a solid maintenance plan – and this has it’s own costs (and potential for downtime).

So…………… choosing a GOOD clustering key EARLY is very important!

Otherwise, the problems can start piling up!

 

via: http://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/