Modificar el Firewall de SQL Azure desde nuestra aplicacion.

Para lo que aun no han usado SQL Azure, este tiene la funcionalidad de crear reglas para las direcciones ip, que este debe aceptar conexiones.
Para hacer esto solo tenemos que ir a https://sql.azure.com/ ,

indentificarnos con nuestro Live ID, ir al proyecto que queremos modificar, ir a la pestana de las Opciones del Firewall, y agregar la regla con el rango de IP(s)
Pero como podemos hacer esto desde nuestra propia aplicación?
Para esto haremos la siguiente aplicación:

  • Abrimos vsto 2008
  • Creamos una nueva aplicación de consola
  • Luego creamos una nueva clase, la llamaremos FirewallRule.cs y ponemos el siguiente código:
  1: public class FirewallRule
  2: {
  3: public FirewallRule (string name, string startIp, string endIp)
  4: {
  5:  Name = name;
  6:  StartIp = IPAddress.Parse (startIp);
  7:  EndIp = IPAddress.Parse (endIp);
  8: }
  9:  public string Name {get; set ;}
 10:  public IPAddress StartIp { get; set; }
 11:  public IPAddress EndIp { get; set; }
 12: }
  • Luego agregamos otra clase llamada Firewall.cs, y ponemos el siguiente código:
  1: public Firewall(string server, string login, string password)
  2: {
  3:     ServerName = server;
  4:     Login = login;
  5:     Password = password;
  6:
  7:     SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
  8:     builder.DataSource = string.Format("tcp:{0}.database.windows.net,1433",
                     ServerName);
  9:     builder.InitialCatalog = "master";
 10:     builder.UserID = Login;
 11:     builder.Password = Password;
 12:     builder.Pooling = true;
 13:     MasterConnectionString = builder.ToString();
 14: }
  • Justo debajo agregamos el siguiente metodo:
  1: public List<FirewallRule> GetRules()
  2: {
  3:     List<FirewallRule> rules = new List<FirewallRule>();
  4:
  5:     using (SqlConnection conn = new SqlConnection(MasterConnectionString))
  6:     using (SqlCommand cmd = conn.CreateCommand())
  7:     {
  8:         conn.Open();
  9:         cmd.CommandText = "SELECT name, start_ip_address, end_ip_address
              FROM sys.firewall_rules";
 10:
 11:         using (SqlDataReader reader = cmd.ExecuteReader())
 12:         {
 13:             while (reader.Read())
 14:             {
 15:                 rules.Add(new FirewallRule(reader["name"] as string,
                             reader["start_ip_address"] as string,
 16:                         reader["end_ip_address"] as string));
 17:             }
 18:         }
 19:     }
 20:     return rules;
 21: }
  • Luego en Program.cs, agregamos el siguiente método:
  1: static void PrintAllRules(Firewall firewall)
  2: {
  3:     var rules = firewall.GetRules();
  4:
  5:     foreach (var rule in rules)
  6:     {
  7:         System.Console.WriteLine("Name:'{0}' StartIP:'{1}' EndIP:'{2}'",
             rule.Name, rule.StartIp, rule.EndIp);
  8:     }
  9:
 10:     Console.WriteLine();
 11: }
  • Agregamos algunas variables,
  1: static string serverName = "REPLACE_WITH_SERVERNAME";
  2: static string userName = "REPLACE_WITH_USERNAME";
  3: static string password = "REPLACE_WITH_PASSWORD";
  4: static Firewall firewall = new Firewall(serverName, userName, password);
  • luego agregamos el siguiente código en la función main:
  1: Console.WriteLine("Current Firewall Rules...");
  2: PrintAllRules(firewall);
  3: System.Console.ReadLine();

Ahora como agregar reglas?

  • En la clase Firewall agregamos el siguiente método:
  1: public void SetFirewallRule(FirewallRule rule)
  2: {
  3:     using (SqlConnection conn = new SqlConnection(MasterConnectionString))
  4:     using (SqlCommand cmd = conn.CreateCommand())
  5:     {
  6:         conn.Open();
  7:         cmd.CommandText = "sp_set_firewall_rule";
  8:         cmd.CommandType = CommandType.StoredProcedure;
  9:
 10:         cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = rule.Name;
 11:         cmd.Parameters.Add("@start_ip_address", SqlDbType.VarChar).Value = rule.StartIp.ToString();
 12:         cmd.Parameters.Add("@end_ip_address", SqlDbType.VarChar).Value = rule.EndIp.ToString();
 13:         cmd.ExecuteNonQuery();
 14:     }
 15: }
  • Este método lo podemos probar si agregamos el siguiente código en la función main del programa
  1: var startIp = "10.0.0.0";
  2: var endIp = "10.0.0.255";
  3: var name = "IP Example 1";
  4: var firewallRule = new FirewallRule(name, startIp, endIp);
  5: firewall.SetFirewallRule(firewallRule);
  6: Console.WriteLine("After Adding a New Rule...");
  7: PrintAllRules(firewall);
  8: System.Console.ReadLine();

Para borrar una Regla?

  • Volvemos a modificar la clase Firewall.cs y agregamos el siguiente método:
  1: public void DeleteFirewallRule(string name)
  2: {
  3:     using (SqlConnection conn = new SqlConnection(MasterConnectionString))
  4:     using (SqlCommand cmd = conn.CreateCommand())
  5:     {
  6:         conn.Open();
  7:         cmd.CommandText = "sp_delete_firewall_rule";
  8:         cmd.CommandType = CommandType.StoredProcedure;
  9:
 10:         cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;
 11:         cmd.ExecuteNonQuery();
 12:     }
 13: }

El método lo podemos probar con el siguiente código:

  1: firewall.DeleteFirewallRule("IP Example 1");
  2: Console.WriteLine("After Deleting Firewall Rule, IP Example 1");
  3: PrintAllRules(firewall);
  4: System.Console.ReadLine();

Hasta La Proxima.. Dejen sus comentarios..

2 comments

Leave a comment

Your email address will not be published. Required fields are marked *