Search

D.R.Y. code

just show me the code

Wednesday, August 4, 2010

JSON Serializer

protected string GetProjectData()
{ 
    IProjectService _service = StructureMap.ObjectFactory.GetInstance<IProjectService>();
    JavaScriptSerializer js = new JavaScriptSerializer();
    return js.Serialize(_service.Get());
}
 
 

[{"Id":1,"Client":"dfsf","Name":"dfsf","LeadDeveloper":"dfsf","ProjectManager":"dfsf",

"PercentComplete":23,"KickOffDate":"\/Date(1262325600000)\/",

"LaunchDate":"\/Date(1285909200000)\/","ModifiedDate":"\/Date(1265832196070)\/",

"ModifiedBy":"dfsf"}]

dyanmic data partial class meta data

namespace DynamicData.Code.DataAccess.Sql.Dbml
{
    [MetadataType(typeof(GameMetadata))]
    public partial class Game
    { 
    }
    public class GameMetadata
    {
        public object HomeTeamId {get; set;}
        public object AwayTeamId { get; set; }
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        //[Range(0,100, ErrorMessage="enter a quanity between ")]
        public object Date { get; set; }
        public object Line { get; set; }
        public object HomeScore { get; set; }
        public object AwayScore { get; set; }
        public object WeekId { get; set; } 
    }
}

Tuesday, February 16, 2010

Javascript RegEx

this will format the 2nd column to nowrap

will also replace 'xxxx' with <b>xxx</b> in the 5th column

   42 
   43     <script type="text/javascript">
   44         $(function() { 
   45             $('tr>td:nth-child(2)').css('white-space', 'nowrap'); 
   46             $('tr>td:nth-child(5)').each(function() {  
   47                 var regex = new RegExp("\'(.[^ ]*)\'", "g"); // look for  'name'   g=globaly
   48                 var replace = '<b>$1</b>';                       // turns 'name'  =>  <b>name</b>
   49                 var t = $(this).text().replace(regex, replace);
   50                 $(this).html(t); 
   51             }); 
   52         });
   53     </script>

Tuesday, September 29, 2009

Xml Literals in vb

Here I am creating an XElement in C#

   19         public static XElement PropertyTable(List<Property> propertyList)
   20         {
   21             XElement root = new XElement("div");
   22             root.Add(new XElement("div"
   23                 , new XAttribute("class", "propertyCount hand")
   24                 , string.Format("{0} properties", propertyList.Count)));
   25             XElement tableElement = new XElement("table", new XAttribute("class", "propertyTable"));
   26             root.Add(tableElement);
   27             XElement headerRow = new XElement("tr");
   28             headerRow.Add(new XElement("th", "Code"));
   29             headerRow.Add(new XElement("th", "Value"));
   30             tableElement.Add(headerRow);
   32
   33             foreach (Property p in propertyList)
   34             {
   35                 XElement projectRow = new XElement("tr");
   36                 projectRow.Add(new XElement("td", p.Code));
   37                 projectRow.Add(new XElement("td", p.Value));
   38                 tableElement.Add(projectRow);
   39             }
   40             return root;
   41         }

Here I am creating the EXACT SAME XElement in VB using xml literals


   19     Public Function PropertyTable(ByVal propertyList As List(Of [Property])) As XElement
   20       Dim root = <div>
   21                    <div class="propertyCount hand"><%= String.Format("{0} properties", propertyList.Count) %></div>
   22                    <table class="propertyTable">
   23                      <tr>
   24                        <th>Code</th>
   25                        <th>Value</th>
   26                      </tr>
   27                      <%= From p In propertyList Select _
   28                        <tr>
   29                          <td><%= p.Code %></td>
   30                          <td><%= p.Value %></td>
   31                        </tr> %>
   32                    </table>
   33                  </div>
   34       Return root
   35     End Function  

which would you rather read?  

Tuesday, July 7, 2009

Using jQuery with ASP .NET

.............

.............
thanks to dotnetslackers
.............

Page.aspx
...........

    3
    4 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    5
    6     <div>
    7         <input id="name" type="text" />
    8         <input id="number" type="text" /><br />
    9         <br />
   10         <input id="Button1" style="width: 158px" type="button" value="button" 
   11             language="javascript"  />&nbsp;
   12     </div>  
   13
   14 </asp:Content>
   15 <asp:Content ID="Content3" ContentPlaceHolderID="javascript" runat="server">
   16     <script src="../Content/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
   17     <script> 
   18         $(document).ready(function() {
   19             $("#Button1").click(function(event) {
   20                 $.ajax({
   21                     type: "POST",
   22                     url: "SimpleService.asmx/SayHelloJson",
   23                     // Looks like this           {'Name': 'Payton', 'Number': '34'} check it in firefox
   24                     data: "{'Name': '" + $('#name').val() + "', 'Number': '" + $('#number').val() + "'}",
   25                     contentType: "application/json; charset=utf-8",
   26                     dataType: "json",
   27                     success: function(msg) {
   28                         AjaxSucceeded(msg);
   29                     },
   30                     error: AjaxFailed
   31                 });
   32             });
   33         }); 
   34        function AjaxSucceeded(result) {  
   35            alert(result.d);  
   36        }  
   37        function AjaxFailed(result) {  
   38            alert(result.status + ' ' + result.statusText);  
   39        }     
   40     </script> 
   41 </asp:Content>

.............

SimpleService.asmx.cs

.............



    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Web;
    5 using System.Web.Services;
    6 using System.Web.Services.Protocols;
    7
    8 namespace Ajax.Web.Public
    9 {
   10     /// <summary>
   11     /// Summary description for SimpleService
   12     /// </summary>
   13     [WebService(Namespace = "http://tempuri.org/")]
   14     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   15     [System.ComponentModel.ToolboxItem(false)]
   16     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
   17     [System.Web.Script.Services.ScriptService]
   18     public class SimpleService : System.Web.Services.WebService
   19     {
   28         [WebMethod]
   29         public string SayHelloJson(String Name, String Number)
   30         {
   31             return "Your Name=" + Name + " \nYour Number=" + Number;
   32         }
   33     }
   34 }


.............

Wednesday, June 24, 2009

call javascript from code behind

    8     <asp:UpdatePanel ID="UpdatePanel1" runat="server"
    9         UpdateMode="Conditional" >
   10         <ContentTemplate>
   12             <asp:Button ID="Button1" runat="server" Text="Button"
   13                 onclick="Button1_Click" />
   14         </ContentTemplate>
   15     </asp:UpdatePanel>

.................


   17         protected void Button1_Click(object sender, EventArgs e)
   18         {
   21             string script = "alert('Message')";
   22             ScriptManager.RegisterClientScriptBlock(UpdatePanel1,
   23                 typeof(UpdatePanel), "jscript", script, true);
   25         }
 
thanks to link

Tuesday, June 16, 2009

jquery ajax post

....

   93
   94 <div id="Result">Click here for current time</div>

....


   99     <script language="javascript">
  100
  101      //Set up the jQuery Char Counter for text area
  102         $(document).ready(function() {
  104             // Add the page method call as an onclick handler for the div.
  105             $("#Result").click(function() {
  106                 $.ajax({
  107                     type: "POST",
  108                     url: "Main.aspx/GetDate",
  109                     data: "{}",
  110                     contentType: "application/json; charset=utf-8",
  111                     dataType: "json",
  112                     success: function(msg) {
  113                         // Replace the div's content with the page method's return.
  114                         $("#Result").text(msg.d);
  115                     },
  116                     error: function() {
  117                         alert('error');
  118                     } 
  119                 }); 
  120             }); 
  121         });
  122      </script>

Main.aspx.cs ....


   30         [WebMethod]
   31         public static string GetDate()
   32         {
   33             return DateTime.Now.ToString();
   34         }



....

Monday, June 1, 2009

passing data in an ntier application

http://stackoverflow.com/questions/917457



How do you pass data to layers in an n-tier application? I have mapped out 3 different methods.

A) generic .net objects generic data tables, Hashtables, generic datasets, strings, ints etc... then using the datasets to fill your business objects which get sent to the UI layer.

alt text

http://dabbleboard.com/draw?b=eiu165&i=26&c=54eef6f1ac01f03c85919518f4a24e798e57e133

Pro- No extra layers needed Con- Have to work with Generic datasets and tables in the business layer

B) using an entities layer that the other layers would reference. This layer would contain either strongly typed datasets or Plain Old C Objects. The objects would be mostly container data and very little logic. these would be the same objects sent to the UI layer.

alt text

http://dabbleboard.com/draw?b=eiu165&i=6&c=d0c2b346894a96b12bd3867f630e474a2af098fa

Pro- working with the same classes in all layers Con- adding a reference to entities.dll to all layers

C) use data transfer objects (conatiner objects only) defined in the DataAccess Layer. then using those objects to fill business objects which get sent to the UI layer.

alt text

http://dabbleboard.com/draw?b=eiu165&i=27&c=f886efa3f9d5eb4b45ddb02361c79cdcdaec0a9b

Pro- the business layer would not have to work with generic classes Con- working with two types of objects and you would have to hydrate the business objects with the transfer objects

We had a discussion at work and wanted to see what the community thought. I also added a link to the dabbleboard. please copy and create instead of editing.
Thanks

Answer:http://stackoverflow.com/questions/917457

Wednesday, May 27, 2009

forms authentication

...........

   38     <authentication mode="Forms">
   39       <forms loginUrl="~/Admin/Login.aspx" defaultUrl="~/Admin/Login.aspx"  protection="All" timeout="60"> 
   40         <credentials passwordFormat="Clear">
   41           <user name="ff" password="xxxxxx"/>
   42           <user name="someguy" password="xxxxxx"/>
   43         </credentials>
   44       </forms>
   45     </authentication>
   46     <authorization>
   47       <allow users="?/>
   48       <allow users="*">
   49     </authorization>

...........


  118   <location path="Public">
  119     <system.web>
  120       <authorization>
  121         <allow users="?"/>
  122       </authorization>
  123     </system.web>
  124   </location>
  125   <location path="Content">
  126     <system.web>
  127       <authorization>
  128         <allow users="?"/>
  129       </authorization>
  130     </system.web>
  131   </location>
  132   <location path="Admin">
  133     <system.web>
  134       <authorization>
  135         <allow users="ff"/>
  136         <deny users="*"/>
  137         <!--<allow users="?"/>-->
  138       </authorization>
  139     </system.web>
  140   </location>
  141   <location path="Admin/Login.aspx">
  142     <system.web>
  143       <authorization>
  144         <allow users="?"/>
  145       </authorization>
  146     </system.web>
  147   </location>


...........


   17
   18     protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
   19     {
   20         if (FormsAuthentication.Authenticate(this.Login1.UserName, this.Login1.Password))
   21             FormsAuthentication.RedirectFromLoginPage(this.Login1.UserName, true); 
   22     }




...........




Thanks to this link

Friday, May 22, 2009

powershell rename recurse

get-Childitem C:\Root\Dev\Drycode\Source * -recurse | rename-item -newName { $_.Name -replace 'XTempNameX', 'DryCode' } -whatif

(Get-Content C:\Root\Dev\Drycode\Source\NNNNNNNNN.txt) |
Foreach-Object {$_ -replace "NNNNNNNNN", "@@@@@@@@@@@@@@@@"} |
Set-Content C:\Root\Dev\Drycode\Source\NNNNNNNNN.txt -whatif

NNNNNNNNN.txt
asNNNNNNNNNdfasdf
saNNNNNNNNNdf
v fsda
faNNNNNNNNNsd
wefwef
sdfasNNNNNNNNN
vdafdsafasfas
NNNNNNNNN
NNNNNNNNN.txt after
as@@@@@@@@@@@@@@@@dfasdf
sa@@@@@@@@@@@@@@@@df
v fsda
fa@@@@@@@@@@@@@@@@sd
wefwef
sdfas@@@@@@@@@@@@@@@@
vdafdsafasfas
@@@@@@@@@@@@@@@@



foreach ($file in get-Childitem -recurse)
{
$file.directoryName + " " +$file.name + " " +$file.length
}


get-Childitem *NNNN* | get-member -membertype property


helpful links
link1
link2
link3
link4
link5
link6

Contributors