Tuesday, April 3, 2012

Entity Framework ITHotList Controller

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.Entity;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using ITHotList.Models;
  9. using System.Web.Security;
  10.  
  11. namespace ITHotList.Controllers
  12. {
  13.     public class HotListController : Controller
  14.     {
  15.         private HotListEntities db = new HotListEntities();
  16.  
  17.         //
  18.         // GET: /HotList/
  19.  
  20.         [Authorize]
  21.         public ViewResult Index()
  22.         {
  23.  
  24.             MembershipUser user = Membership.GetUser();
  25.             Guid userId = (Guid)user.ProviderUserKey;
  26.  
  27.             return View(db.HotLists.Where(hotlist => hotlist.UserId == userId).OrderByDescending(hotlist => hotlist.CreateDate).ToList());
  28.         }
  29.  
  30.         //
  31.         // GET: /HotList/Details/5
  32.         [Authorize]
  33.         public ViewResult Details(int id)
  34.         {
  35.             HotList hotlist = db.HotLists.Find(id);
  36.             return View(hotlist);
  37.         }
  38.  
  39.         //
  40.         // GET: /HotList/Create
  41.         [Authorize]
  42.         public ActionResult Create()
  43.         {
  44.  
  45.             HotList hotlistModel = new HotList();
  46.             hotlistModel.Name = "Name";
  47.             hotlistModel.Resources.Add(new Resource() { Name = "", Availability= "", CurrentLocation="", ImmigrationStatus ="", JobRole="", PreferredLocation="", Rate ="", LinkToResume="", Skill="", YearsOfExp = 0   });
  48.             return View(hotlistModel);
  49.  
  50.         }
  51.  
  52.         //
  53.         // POST: /HotList/Create
  54.  
  55.         [Authorize]
  56.         [HttpPost]
  57.         public JsonResult Create(HotList receivedhotlist)
  58.         {
  59.  
  60.             // never trust what has come from ui.
  61.  
  62.             string message = string.Empty;
  63.  
  64.             try
  65.             {
  66.                 HotList hotlist = new HotList();
  67.  
  68.                 if (ModelState.IsValid)
  69.                 {
  70.                     MembershipUser user = Membership.GetUser();
  71.                     Guid userId = (Guid)user.ProviderUserKey;
  72.                     hotlist.UserId = userId;
  73.  
  74.                     try
  75.                     {
  76.  
  77.                         hotlist.Active = true;
  78.                         hotlist.Name = receivedhotlist.Name;
  79.                         hotlist.CreateDate = DateTime.Now;
  80.  
  81.                         var profile = Profile.GetProfile(user.UserName);
  82.  
  83.                         if (profile.CompanyName != null)
  84.                         {
  85.                             hotlist.CompanyName = profile.CompanyName;
  86.                         }
  87.  
  88.                         if (user.Email != null)
  89.                         {
  90.                             hotlist.Email = user.Email;
  91.                         }
  92.  
  93.                         if (profile.PrimaryPhoneNumber != null)
  94.                         {
  95.                             hotlist.PrimaryPhoneNumber = profile.PrimaryPhoneNumber;
  96.                         }
  97.  
  98.                         if (profile.PrimaryExt != null)
  99.                         {
  100.                             hotlist.PrimaryExt = profile.PrimaryExt;
  101.                         }
  102.  
  103.                         if (profile.SecondaryPhoneNumber != null)
  104.                         {
  105.                             hotlist.SecondaryPhoneNumber = profile.SecondaryPhoneNumber;
  106.                         }
  107.  
  108.                         if (profile.SecondaryExt != null)
  109.                         {
  110.                             hotlist.SecondaryExt = profile.SecondaryExt;
  111.                         }
  112.  
  113.  
  114.                         if (profile.Fax != null)
  115.                         {
  116.                             hotlist.Fax = profile.Fax;
  117.                         }
  118.  
  119.                         // Error is happening here.. need to fix it.
  120.  
  121.                     }
  122.                     catch { }
  123.  
  124.                     foreach (Resource receivedresource in receivedhotlist.Resources)
  125.                     {
  126.                         Resource resource = new Resource();
  127.  
  128.                         resource.Active = true;
  129.                         resource.UserId = userId;
  130.                         resource.JobRole = receivedresource.JobRole;
  131.                         resource.Availability = receivedresource.Availability;
  132.  
  133.                         resource.CurrentLocation = receivedresource.CurrentLocation;
  134.                         resource.ImmigrationStatus = receivedresource.ImmigrationStatus;
  135.                         resource.LinkToResume = receivedresource.LinkToResume;
  136.                         resource.Name = receivedresource.Name;
  137.                         resource.PreferredLocation = receivedresource.PreferredLocation;
  138.                         resource.Rate = receivedresource.Rate;
  139.                         resource.Skill = receivedresource.Skill;
  140.                         resource.YearsOfExp = receivedresource.YearsOfExp;
  141.  
  142.                         resource.HotLists.Add(hotlist);
  143.                         hotlist.Resources.Add(resource);
  144.  
  145.                         db.Resources.Add(resource);
  146.  
  147.                     }
  148.  
  149.                     db.HotLists.Add(hotlist);
  150.  
  151.                     db.SaveChanges();
  152.  
  153.                     //do the persistence logic here
  154.                     message = "SUCCESS";
  155.  
  156.                 }
  157.                 else
  158.                 {
  159.                     message = "modelstate is invalid";
  160.                 }
  161.  
  162.                
  163.             }
  164.             catch (Exception ex)
  165.             {
  166.                 message = ex.Message.ToString();
  167.             }
  168.             
  169.             return Json(message);
  170.         }
  171.  
  172.  
  173.  
  174.         //[HttpPost]
  175.         //public ActionResult Create(HotList hotlist)
  176.         //{
  177.         //    if (ModelState.IsValid)
  178.         //    {
  179.  
  180.         //        MembershipUser user = Membership.GetUser();
  181.         //        Guid userId = (Guid)user.ProviderUserKey;
  182.         //        hotlist.UserId = userId;
  183.         //        hotlist.CreateDate = DateTime.Now;
  184.         //        db.HotLists.Add(hotlist);
  185.         //        db.SaveChanges();
  186.         //        return RedirectToAction("Index");
  187.         //    }
  188.  
  189.         //    return View(hotlist);
  190.         //}
  191.  
  192.         //
  193.         // GET: /HotList/Edit/5
  194.         [Authorize]
  195.         public ActionResult Edit(int id)
  196.         {
  197.             HotList hotlist = db.HotLists.Find(id);
  198.             return View(hotlist);
  199.         }
  200.  
  201.         //
  202.         // POST: /HotList/Edit/5
  203.         [Authorize]
  204.         [HttpPost]
  205.         public ActionResult Edit(HotList hotlist)
  206.         {
  207.             if (ModelState.IsValid)
  208.             {
  209.                 db.Entry(hotlist).State = EntityState.Modified;
  210.                 db.SaveChanges();
  211.                 return RedirectToAction("Index");
  212.             }
  213.             return View(hotlist);
  214.         }
  215.  
  216.         //
  217.         // GET: /HotList/Delete/5
  218.         [Authorize]
  219.         public ActionResult Delete(int id)
  220.         {
  221.             HotList hotlist = db.HotLists.Find(id);
  222.             return View(hotlist);
  223.         }
  224.  
  225.         //
  226.         // POST: /HotList/Delete/5
  227.         [Authorize]
  228.         [HttpPost, ActionName("Delete")]
  229.         public ActionResult DeleteConfirmed(int id)
  230.         {
  231.             HotList hotlist = db.HotLists.Find(id);
  232.             db.HotLists.Remove(hotlist);
  233.             db.SaveChanges();
  234.             return RedirectToAction("Index");
  235.         }
  236.  
  237.         protected override void Dispose(bool disposing)
  238.         {
  239.             db.Dispose();
  240.             base.Dispose(disposing);
  241.         }
  242.     }
  243. }

Monday, March 12, 2012

How to test your configuration on servers to eliminate Issues before opening to production.










  
Code Snippet
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NewPage.aspx.cs" Inherits="TestConnection_NewPage" %>
  2. DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html >
  4. <head id="Head1" runat="server">    
  5. head>
  6. <title>jQuery UI Tabs - Open on mouseovertitle>    
  7. <link type="text/css" href="jquery-ui-1.8.custom.css" rel="Stylesheet"/>
  8. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js">script>    
  9. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.js">script>
  10.     
  11.     
  12.     <style type="text/css">.style3 { FONT-SIZE: x-large; COLOR: #ffffff }
  13.         .style4 { FONT-FAMILY: Verdana; TEXT-ALIGN: center }
  14.         .style5 { FONT-SIZE: medium }
  15.         .style6 { FONT-WEIGHT: bold; FONT-SIZE: medium; FILTER: dropshadow(color=#000000,offx=2,offy=2); COLOR: #0b77d3; FONT-FAMILY: Verdana; TEXT-ALIGN: center }
  16.         .moduleGroupDivStyle {width:100%; }
  17.         .appGroupHeadingStyle {width:100%; height:20px; padding-left:20px; text-align:left; vertical-align:bottom; font-weight:bold; font-size:12px; background-color:LightGrey;}
  18.         .RadioButtonStyle {font-size:11px; }
  19.     style>
  20.  
  21. <script type="text/javascript">
  22.     $(function () {
  23.         $("#tabs").tabs({
  24.             event: 'mouseover'
  25.         });
  26.     });
  27.     script>
  28.  
  29. <body>
  30.  
  31. <div class="demo">
  32. <div id="displayLoading"><span style="background-color:Yellow;font-size:larger;">Loading.... span>div>
  33. <table cellspacing="0" cellpadding="0" width="100%" border="0">
  34.                 <tbody>
  35.                     <tr>
  36.                            <td valign="bottom" nowrap width="29%" background="di1.gif" height="55">
  37.                              td>
  38.                         <td class="style3" nowrap background="di1.gif" height="55">
  39.                             Validate Web.config td>
  40.                         <td valign="bottom" nowrap width="22%" background="di1.gif">
  41.                              td>
  42.                     tr>
  43.                 tbody>
  44. table>
  45. <table width="70%">
  46. <tr>
  47.     <td width="10%"> td><td style="height:1cm"> td>
  48. tr>
  49.  
  50. <tr>
  51.     <td width="10%"> td><td><center><h5>Webservices, nHibernate Mapping Files, Database Connectionsh5>center>td>
  52. tr>
  53. <tr>
  54.     <td> td><td> td>
  55. tr>
  56. <tr>
  57. <td>
  58.  
  59. td>
  60. <td>
  61. <div id="tabs">
  62.     <ul>
  63.         <li><a href="#tabs-1">Web Service URLsa>li>
  64.         <li><a href="#tabs-2">Nhibernate Mappinga>li>
  65.         <li><a href="#tabs-3">Connection Stringa>li>
  66.     ul>
  67.     <div id="tabs-1">
  68.         <p>
  69.         
  70.         <asp:Table ID="wsListTable" runat="server" BorderWidth="1" BackColor="AliceBlue"
  71.             Font-Size="Larger" CellPadding="2" CellSpacing="2" BorderColor="Black">
  72.             <asp:TableRow BorderWidth=1 Font-Bold="true">
  73.                 <asp:TableCell BorderWidth="1" Width="10%" VerticalAlign="Middle" align="center">Serial Noasp:TableCell>
  74.                 <asp:TableCell BorderWidth="1" Width="40%">URL/Connectionasp:TableCell>
  75.                 <asp:TableCell BorderWidth="1" Width="10%" align="center">Statusasp:TableCell>
  76.             asp:TableRow>
  77.         asp:Table>   
  78.         <br/>
  79.         <br/>
  80.         <button id="TestConn">Test Webservice button><span style="background-color:Yellow;font-size:larger;" id="lblstatus">span>
  81.     p>
  82.     div>
  83.     <div id="tabs-2">
  84.         <p>
  85.             <span id="TestConnection">span>
  86.              <br/>
  87.             <br/>
  88.             <button id="TestDatabase">Test Mappingbutton>
  89.         p>
  90.     div>
  91.     <div id="tabs-3">
  92.         <p><asp:Table ID="wsDatabaseConnection" runat="server" BorderWidth="1" BackColor="AliceBlue"
  93.             Font-Size="Larger" CellPadding="2" CellSpacing="2" BorderColor="Black">
  94.         <asp:TableRow BorderWidth=1 Font-Bold="true">
  95.             <asp:TableCell BorderWidth="1" Width="10%" VerticalAlign="Middle" align="center">Nameasp:TableCell>
  96.             <asp:TableCell BorderWidth="1" Width="30%">Connection stringasp:TableCell>
  97.             <asp:TableCell BorderWidth="1" Width="10%" align="center">Providerasp:TableCell>
  98.         asp:TableRow>
  99.     asp:Table> p>
  100.     div>
  101. div>
  102. td>
  103. tr>
  104. table>
  105. div>
  106.  
  107. <script type="text/javascript">
  108.  
  109.      $(document).ready(function () {
  110.          $("#displayLoading").hide();
  111.      });
  112.      $("#TestDatabase").click(function () {
  113.  
  114.          var webMethod = 'newpage.aspx/TestAllMapping'
  115.          var resultId = "#ResultData";
  116.  
  117.  
  118.          $.ajax({
  119.              type: "POST",
  120.              url: webMethod,
  121.              data: "{'name': '" + $(this).attr("id") + "'}",
  122.              contentType: "application/json; charset=utf-8",
  123.              dataType: "json",
  124.              success: function (msg) {
  125.                  $("#TestConnection").html(msg.d);
  126.              },
  127.              error: AjaxFailed
  128.          });
  129.      });
  130.  
  131.      $("#TestConn").click(function () {
  132.  
  133.          resetResults();
  134.          testConnections();
  135.  
  136.      });
  137.  
  138.      function resetResults() {
  139.  
  140.          $("td").each(function () {
  141.              var resultId = "#" + $(this).attr("id") + "Result";
  142.              $(resultId).text("");
  143.          });
  144.      }
  145.  
  146.      function testConnections() {
  147.          $("td").each(function () {
  148.              if ($(this).text().substring(0, 4) == "http") {
  149.  
  150.                  var webMethod = 'newpage.aspx/TestHTTP'
  151.                  var resultId = "#" + $(this).attr("id") + "Result";
  152.                  $.ajax({
  153.                      type: "POST",
  154.                      url: webMethod,
  155.                      timeout: 3000,
  156.                      data: "{'name': '" + $(this).attr("id") + "'}",
  157.                      contentType: "application/json; charset=utf-8",
  158.                      dataType: "json",
  159.                      success: function (msg) {
  160.                          if (msg.d == "False") {
  161.  
  162.                          }
  163.                          $(resultId).html(msg.d);
  164.  
  165.                      },
  166.                      async: false,
  167.                      error: AjaxFailed
  168.                  });
  169.              }
  170.          });
  171.      }
  172.  
  173.      function AjaxFailed(result) {
  174.          alert(result.status + ' ' + result.statusText);
  175.      }
  176.  
  177.     script>
  178. body>
  179. html>


Code Snippet
  1. using System;
  2. using System.Collections;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.OracleClient;
  6. using System.Data.SqlClient;
  7. using System.Net;
  8. using System.Text;
  9. using System.Web.UI.WebControls;
  10.  
  11.  
  12. public partial class TestConnection_NewPage : System.Web.UI.Page
  13. {
  14.     protected void Page_Load(object sender, EventArgs e)
  15.     {
  16.  
  17.         int nCounter = 0;
  18.  
  19.  
  20.         foreach (string appKey in ConfigurationManager.AppSettings.AllKeys)
  21.         {
  22.             string appKeyValue = ConfigurationManager.AppSettings.Get(appKey);
  23.             if (appKeyValue.Contains("http") && !appKeyValue.Contains("swe"))
  24.             {
  25.                 TableRow tRow = new TableRow();
  26.                 tRow.BorderWidth = 1;
  27.                 // Create a new cell and add it to the row.
  28.                 TableCell tCell1 = new TableCell();
  29.                 tCell1.Text = (++nCounter).ToString();
  30.                 tCell1.BorderWidth = 1;
  31.                 tRow.Cells.Add(tCell1);
  32.  
  33.                 TableCell tCell2 = new TableCell();
  34.                 tCell2.Text = appKeyValue;
  35.                 tCell2.BorderWidth = 1;
  36.                 tCell2.ID = appKey;
  37.                 tRow.Cells.Add(tCell2);
  38.  
  39.  
  40.                 TableCell tCell3 = new TableCell();
  41.                 tCell3.BorderWidth = 1;
  42.                 tCell3.ID = appKey.Trim() + "Result";
  43.                 tRow.Cells.Add(tCell3);
  44.                 wsListTable.Rows.Add(tRow);
  45.  
  46.             }
  47.         }
  48.  
  49.         foreach (ConnectionStringSettings connection in ConfigurationManager.ConnectionStrings)
  50.         {
  51.             string name = connection.Name;
  52.             string provider = connection.ProviderName;
  53.             string connectionString = connection.ConnectionString;
  54.             string statusCheck = string.Empty;
  55.  
  56.             TableRow tRow = new TableRow();
  57.             tRow.BorderWidth = 1;
  58.             // Create a new cell and add it to the row.
  59.             TableCell tCell1 = new TableCell();
  60.             tCell1.Text = name;
  61.             tCell1.BorderWidth = 1;
  62.             tRow.Cells.Add(tCell1);
  63.  
  64.             TableCell tCell2 = new TableCell();
  65.             tCell2.Text = connectionString;
  66.             tCell2.BorderWidth = 1;
  67.             tCell2.ID = name;
  68.             tRow.Cells.Add(tCell2);
  69.  
  70.             try
  71.             {
  72.                 if (provider == "System.Data.SqlClient")
  73.                 {
  74.                     SqlConnection conn = new SqlConnection(connectionString);
  75.  
  76.                     conn.Open();
  77.                     if (conn.State == ConnectionState.Open)
  78.                         statusCheck = "Success";
  79.                 }
  80.                 if (provider == "System.Data.OracleClient")
  81.                 {
  82.                     OracleConnection conn = new OracleConnection(connectionString);
  83.                     conn.Open();
  84.                     if (conn.State == ConnectionState.Open)
  85.                         statusCheck = "Success";
  86.  
  87.                 }
  88.             }
  89.             catch (Exception exp)
  90.             {
  91.                 statusCheck = exp.Message.ToString();
  92.             }
  93.  
  94.             TableCell tCell3 = new TableCell();
  95.             tCell3.BorderWidth = 1;
  96.             tCell3.ID = name.Trim() + "Result";
  97.             tCell3.Text = statusCheck;
  98.             tRow.Cells.Add(tCell3);
  99.             wsDatabaseConnection.Rows.Add(tRow);
  100.  
  101.         }
  102.     }
  103.     [System.Web.Services.WebMethod]
  104.     public static string TestHTTP(string name)
  105.     {
  106.         //= "url";
  107.         string appKey = name;
  108.         string appKeyValue = ConfigurationManager.AppSettings.Get(appKey);
  109.  
  110.         if (appKeyValue.Contains("http"))
  111.         {
  112.             if (!(appKeyValue.Contains("wsdl") || appKeyValue.Contains("WSDL")))
  113.             {
  114.                 appKeyValue += "?wsdl";
  115.             }
  116.         }
  117.  
  118.         return ConnectionAvailable(appKeyValue) ? "<span style='color:Green'>Passedspan>" : "<span style='color:Red'>Failedspan>";
  119.  
  120.     }
  121.     public static bool ConnectionAvailable(string strServer)
  122.     {
  123.         try
  124.         {
  125.             HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);
  126.  
  127.             HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
  128.             if (HttpStatusCode.OK == rspFP.StatusCode)
  129.             {
  130.                 // HTTP = 200 - Internet connection available, server online
  131.                 rspFP.Close();
  132.                 return true;
  133.             }
  134.             else
  135.             {
  136.                 // Other status - Server or connection not available
  137.                 rspFP.Close();
  138.                 return false;
  139.             }
  140.         }
  141.         catch (WebException)
  142.         {
  143.             // Exception - connection not available
  144.             return false;
  145.         }
  146.     }
  147.  
  148.     [System.Web.Services.WebMethod]
  149.     public static string TestAllMapping()
  150.     {
  151.         StringBuilder stb = new StringBuilder();
  152.  
  153.         stb.AppendFormat("<tr style='height:10'><td><b>{0}b>td><td><b>{1}b>td><td><b>{2}b>td>tr>", "Table Name", "Exception", "Nhibernate Object");
  154.         using (OES.Library.nHibernate.Repository rep = new OES.Library.nHibernate.Repository())
  155.         {
  156.  
  157.             IDictionary allClassMetadata = rep.Session.SessionFactory.GetAllClassMetadata();
  158.             foreach (DictionaryEntry entry in allClassMetadata)
  159.             {
  160.                 try
  161.                 {
  162.  
  163.                     NHibernate.Persister.Entity.SingleTableEntityPersister tableEntity = entry.Value as NHibernate.Persister.Entity.SingleTableEntityPersister;
  164.                     if (tableEntity != null)
  165.                     {
  166.                         int index = tableEntity.ClassMetadata.EntityName.Split('.').Length;
  167.                         if (tableEntity.TableName.Split('.')[1] != tableEntity.ClassMetadata.EntityName.Split('.')[index - 1])
  168.                         {
  169.  
  170.                             rep.Session.CreateCriteria((Type)entry.Key)
  171.                                  .SetMaxResults(0).List();
  172.                         }
  173.                     }
  174.                 }
  175.                 catch (Exception exp)
  176.                 {
  177.  
  178.                     NHibernate.Persister.Entity.SingleTableEntityPersister tableEntity = entry.Value as NHibernate.Persister.Entity.SingleTableEntityPersister;
  179.  
  180.                     stb.AppendFormat("<tr><td>{0}td><td>{1}td><td>{2}td>tr>", tableEntity.TableName, exp.InnerException.Message, entry.Key);
  181.  
  182.  
  183.                 }
  184.             }
  185.             if (stb.Length == 0)
  186.             {
  187.                 stb.Append("Sucess");
  188.             }
  189.         }
  190.         return GenerateTable(stb).ToString();
  191.     }
  192.     private static StringBuilder GenerateTable(StringBuilder sbTableContent)
  193.     {
  194.         StringBuilder sbTable = new StringBuilder();
  195.         sbTable.AppendFormat("<Table cellspacing='0' border='1'>{0}Table>", sbTableContent.ToString());
  196.  
  197.         return sbTable;
  198.     }
  199. }




Friday, February 24, 2012

How to serialize and Object during debugging.

This is different. If you want to serialize an object directly in watch window, without having to goto immediate window, here is the code.

Utility.SerializeObject(quoteByIdResponse)



Code Snippet
  1. public static byte[] SerializeObject(object pObject)
  2.   {
  3.       byte[] xmlvalue = new Byte[0];
  4.  
  5.       MemoryStream memoryStream = new MemoryStream();
  6.       XmlSerializer xs = new XmlSerializer(pObject.GetType());
  7.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
  8.       try
  9.       {
  10.           xs.Serialize(xmlTextWriter, pObject);
  11.           memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
  12.           xmlvalue = memoryStream.ToArray();
  13.       }
  14.       catch (Exception e)
  15.       {
  16.  
  17.       }
  18.       finally
  19.       {
  20.           xmlTextWriter.Close();
  21.           xmlTextWriter = null;
  22.           memoryStream.Close();
  23.           memoryStream = null;
  24.           xs = null;
  25.       }
  26.       return xmlvalue;
  27.   }
  28.  
  29.   public static string SerializeObjectString(object pObject)
  30.   {
  31.       string XmlString = null;
  32.       StringWriter sw = new StringWriter();
  33.       XmlSerializer xs = new XmlSerializer(pObject.GetType());
  34.       try
  35.       {
  36.           xs.Serialize(sw, pObject);
  37.           XmlString = sw.ToString();
  38.       }
  39.       catch (Exception e)
  40.       {
  41.           XmlString = e.Message;
  42.           if (e.InnerException != null)
  43.               XmlString += " Inner Exception:" + e.InnerException.Message;
  44.       }
  45.       finally
  46.       {
  47.           xs = null;
  48.       }
  49.       return XmlString;
  50.   }

Tuesday, January 24, 2012

Weekly reports that needs to be sent manually.


Just want to write out the code for generating weekly reports. It is very boring to run the queries manually then paste in excel and send it out.
 
Code Snippet
  1. using System;
  2. using System.Data.OracleClient;
  3. using System.Text;
  4.  
  5. namespace WeeklyReports
  6. {
  7.  
  8.     public static class DateTimeExtensions
  9.     {
  10.         public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { int diff = dt.DayOfWeek - startOfWeek; if (diff < 0) { diff += 7; } return dt.AddDays(-1 * diff).Date; }
  11.     }
  12.  
  13.  
  14.     public partial class _Default : System.Web.UI.Page
  15.     {
  16.  
  17.  
  18.  
  19.         protected void Page_Load(object sender, EventArgs e)
  20.         {
  21.  
  22.             StringBuilder allTables = new StringBuilder();
  23.  
  24.             using (OracleConnection oraConn = new OracleConnection(@"Data Source=abc.world;Persist Security Info=True;User ID=abc;Password=abc;Unicode=True"))
  25.             {
  26.  
  27.                 DateTime monday = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
  28.                 DateTime sunday = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
  29.                 monday = monday.AddDays(-7);
  30.  
  31.                 for (int ctr = 0; ctr < 10; ctr++)
  32.                 {
  33.  
  34.  
  35.  
  36.                     String strMonday = FormatDateToOracle(monday);
  37.                     String strSunday = FormatDateToOracle(sunday);
  38.  
  39.                    OracleCommand oraCmd = new OracleCommand(@"SELECT applicationname,  COUNT(*) FROM  EM_MONITOR.LOAD_DOT_NET_LOG_ERROR_PRD WHERE error_date BETWEEN '" + strMonday + "' AND '" + strSunday + "' AND   applicationname!='(null)' GROUP BY applicationname ORDER BY COUNT(*) DESC ", oraConn);
  40.  
  41.                   //  OracleCommand oraCmd = new OracleCommand(@"select * from (  SELECT COUNT(*),  MESSAGE FROM EM_MONITOR.LOAD_DOT_NET_LOG_ERROR_PRD WHERE error_date BETWEEN '" + strMonday + "' AND '" + strSunday + "'  AND applicationname!='(null)' GROUP BY MESSAGE ORDER BY COUNT(*) DESC  ) where rownum <= 5 ", oraConn);
  42.  
  43.                     oraConn.Open();
  44.                     OracleDataReader oraDr = oraCmd.ExecuteReader();
  45.  
  46.                     StringBuilder sbTable = new StringBuilder();
  47.  
  48.                     StringBuilder sbRows = new StringBuilder();
  49.  
  50.                     while (oraDr.Read())
  51.                     {
  52.  
  53.                         sbRows.Append("");
  54.                         for (int col = 0; col < oraDr.FieldCount; col++)
  55.                         {
  56.                             sbRows.Append("" + oraDr[col].ToString() + "");
  57.  
  58.                         }
  59.  
  60.                         sbRows.Append("");
  61.  
  62.                     }
  63.  
  64.                     sbTable.Append("" + sbRows + "
    "  + "For week " +  strMonday + " - " + strSunday + "
    "
    );
  65.  
  66.                     allTables.Append(sbTable.ToString() + @"");
  67.                     oraConn.Close();
  68.  
  69.                     monday = monday.AddDays(-7);
  70.                     sunday = sunday.AddDays(-7);
  71.  
  72.                 }
  73.             }
  74.  
  75.             divTables.InnerHtml  = allTables.ToString();
  76.  
  77.         }
  78.  
  79.         private string FormatDateToOracle(DateTime date)
  80.         {
  81.             return date.ToString("dd-MMM-yyyy").ToUpper();
  82.         }
  83.  
  84.       
  85.     }
  86. }

Monday, August 29, 2011

Use regular expressions to save time.

Replace in files...

Utils.GetConfigValue\({"[a-zA-Z0-9_ ]+"}\)

to

System.Configuration.ConfigurationManager.ConnectionStrings\[\1\]

Wednesday, August 3, 2011

Sorting entries in config appsettings.

   How to sort AppSettings without manually missing any keys or important information.
Code Snippet
  1.   private void WriteAppSettingsToFile(string filename)
  2.     {
  3.  
  4.         List<string> lstConfigKeys = new List<string>();
  5.         foreach (string appKey in ConfigurationManager.AppSettings.AllKeys)
  6.         {
  7.             lstConfigKeys.Add(appKey);
  8.         }
  9.  
  10.         lstConfigKeys.Sort();
  11.  
  12.         using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\" + filename + ".txt"))
  13.         {
  14.             foreach (string key in lstConfigKeys)
  15.             {
  16.                 file.WriteLine(string.Format("'{0}', -- {1}", key, ConfigurationManager.AppSettings.Get(key)));
  17.             }
  18.         }
  19.     }

You can modify the code to write the keys in the form of   . Then copy and paste the output to your actual config file. You have all the keys in sorted order.