Tips and Tricks in a world of Mix

http://www.mcdonaldland.info/2007/11/28/40/

http://www.cafepress.com/codergear/5033878

   1: /// <summary>

   2:        /// Convert a single DataRow into an object of type T.

   3:        /// </summary>

   4:        /// <explanation>

   5:        /// where T : class, new() a constraint on the generic parameter. it must be a class (or reference type), 

   6:        /// and must have an parameterless default constructor.

   7:        /// </explanation>

   8:        public static T ConvertDataRowToEntity<T>(DataRow row) where T : class, new()

   9:        {

  10:            Type objType = typeof(T);

  11:            T obj = Activator.CreateInstance<T>(); //hence the new() contsraint of T object 

  12:            Debug.WriteLine(objType.Name + " = new " + objType.Name + "();");

  13:            foreach (DataColumn column in row.Table.Columns)

  14:            {

  15:                ///by column in the table we get the property in objType ignoring the unneeded ones

  16:                PropertyInfo property =  objType.GetProperty(column.ColumnName,   

  17:                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

  18:                if (property == null || !property.CanWrite)

  19:                {

  20:                    Debug.WriteLine("//Property " + column.ColumnName + " not in object");

  21:                    continue; //or throw

  22:                }

  23:                //}

  24:  

  25:                ///in case the type of the property is different from data object type - 

  26:                ///convert it to the right type

  27:                object value = row[column.ColumnName];

  28:                if (value == DBNull.Value) value = null;

  29:                else

  30:                {

  31:                    Type propertyType = property.PropertyType;

  32:                    Type dataObjectType = row[column.ColumnName].GetType();

  33:                    if (propertyType.ToString() != dataObjectType.ToString())

  34:                    {

  35:                        value = Convert.ChangeType(value, propertyType);

  36:                    }

  37:                }

  38:                property.SetValue(obj, value, null);

  39:                Debug.WriteLine("obj." + property.Name + " = row[\"" + column.ColumnName + "\"];");

  40:            }

  41:            return obj;

  42:        }

In html just enter  the buttons

   1: <!DOCTYPE html>

   2: <html xmlns="http://www.w3.org/1999/xhtml">

   3: <head>

   4:     <title></title>

   5:     <script src="global.js"></script>

   6:     <link href="style.css" rel="stylesheet" />

   7: </head>

   8: <body>

   9:      <input type="submit" value="New Table" onClick="generate_table()"/>

  10:      <input type="submit" value="New Row" onClick="addRow()"/>

  11:     <input type="submit" value="Delete Row" onClick="deleteRow()"/>

  12:    

  13: </body>

  14: </html>

 

At javascript pure will create the tags and append to the html existing tags.

CreateRow is extraxted to function for reuse.

   1: function generate_table() {

   2:     // get the reference for the body

   3:     var body = document.getElementsByTagName("body")[0];

   4:  

   5:     // creates a <table> element and a <tbody> element

   6:     var tbl = document.createElement("table");

   7:     var tblBody = document.createElement("tbody");

   8:  

   9:     createRow(tbl);

  10:  

  11:      // put the <tbody> in the <table>

  12:     tbl.appendChild(tblBody);

  13:     // appends <table> into <body>

  14:     body.appendChild(tbl);

  15:   

  16: }

  17:     

  18: function addRow() {

  19:     var table =  document.getElementsByTagName("table")[0];

  20:     createRow(table);

  21: }

  22:  

  23: function createRow(table) {

  24:     var rowCount = table.rows.length;

  25:     var row = table.insertRow(rowCount);

  26:  

  27:     var cell1 = row.insertCell(0);

  28:     var element1 = document.createElement("input");

  29:     element1.type = "checkbox";

  30:     element1.name = "chkbox[]";

  31:     cell1.appendChild(element1);

  32:  

  33:     var cell2 = row.insertCell(1);

  34:     cell2.innerHTML = rowCount + 1;

  35:  

  36:     var cell3 = row.insertCell(2);

  37:     var element2 = document.createElement("input");

  38:     element2.type = "text";

  39:     element2.name = "txtbox[]";

  40:     cell3.appendChild(element2);

  41: }

  42:  

  43: function deleteRow() {

  44:     try {

  45:         var table = document.getElementsByTagName("table")[0];

  46:         var rowCount = table.rows.length;

  47:  

  48:         for (var i = 0; i < rowCount; i++) {

  49:             var row = table.rows[i];

  50:             var chkbox = row.cells[0].childNodes[0];

  51:             if (null != chkbox && true == chkbox.checked) {

  52:                 table.deleteRow(i);

  53:                 rowCount--;

  54:                 i--;

  55:             }

  56:  

  57:  

  58:         }

  59:     } catch (e) {

  60:         alert(e);

  61:     }

  62: }

Heap vs. Stack

The Stack is responsible of what’s been “called”  ,is self-maintaining, meaning that it basically takes care of its own memory management. First in last out – “FILO” .Stack as a series of boxes stacked one on top of the next.When we’re done with the top box (the method is done executing) we throw it away and proceed to use the stuff in the previous box on the top of the Stack.The Stack is like the Stack of shoe boxes in the closet where we have to take off the top one to get to the one underneath it.

Heap is responsible for keeping track of our objects, its purpose is to hold information so anything in our Heap can be accessed at  any time.there are no constraints as to what can be accessed like in the Stack. we can grab what we need quickly.The Heap,handled by Garbage collection (GC), which deals with how to keep the Heap clean.

We have four main types of things we’ll be putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions.

Value Types: from System.ValueType

bool , byte,char,decimal,double,enum,float, struct..

Reference Types: and inherit from System.Object

class ,interface,delegate,object,string

Pointers: Reference to a Type

We don’t explicitly use Pointers, they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is different than a Reference Type in that when we say something is a Reference Type, it means we access it through a Pointer.A Pointer is a chunk of space in memory that points to another space in memory.A Pointer takes up space just like any other thing that we’re putting in the Stack and Heap and its value is either a memory address or null.

 

A Reference Type always goes on the Heap

Value Types and Pointers always go where they were declared.

If the value type is a poco and doesn’t implement some object , than it will enter the Stack.

public int AddFive(int pValue)
          {
               int result;
                result = pValue + 5;
               return result;
          }

heapvsstack5.gif

But if we are dealing with Pointers  even though the members are primitive types it will be entered into stack and point to the object in the heap.

public class MyInt
{
         public int MyValue;
}

public int ReturnValue2()
{
                MyInt x;
                x.MyValue = 3;
                MyInt y;
                y = x;
                y.MyValue = 4;
               return x.MyValue;
  }

heapvsstack13.gif

 

 

Each local variable is also located in Stack as being sent to the methods.

The methods have a GOTO reference (instructions) which direct them where to return after the method completed.

But if we have a big data primitive member, variable , such as some big struct it can overload the Stack.

The resolution is to use ref

Sending Value Type by ref

public void Go()

{

         MyStruct x = new MyStruct();

         DoSomething(ref x);

}

public struct MyStruct

{

            long a, b, c, d, e, f, g, h, i, j, k, l, m;

}

public void DoSomething(ref MyStruct pValue)

{

          // DO SOMETHING HERE….

}

 

 

that way the reference is only entered once in the Stack and if we’d preform that method 1000 times it’ll only add some more pointers to the reference location in the stack.

If our object is big it makes a big difference.

Important – when you are changing the local variable inside the Method where you send value by reference you are actually changing the parameter outside that method also.

 

Sending Reference Type as parameter

both x and pValue – are set into Stack as a Pointer to Object created in the Heap.

public void Go()

{

        MyInt x = new MyInt();

       x.MyValue = 2;

       DoSomething(x);

       Console.WriteLine(x.MyValue.ToString());

}

public void DoSomething(MyInt pValue)

{

            pValue.MyValue = 12345;

}

 

So to conclusion , the reference(the definition of the object) to the object going to the Stack while the Object itself enters the Heap.

If the initialization of the reference is reinitialized to some other Object than accordingly the reference(hence the Pointer) will point to the new Object that will also be created in the Heap.

 

For the objects inside the objects to be unique we would want to implement the IClonable interface initializing the inner object each time we need it . Otherwise we can end up pointing out the same object from different parent objects.

We would implement public object Clone() and will get the object returned as MyObjType .

GC –

JIT and CLR  are using the heap – list of used recourses and all that connected to them is mapped to a graph. GC gets the list of "root" object references to keep from just-in-time (JIT) compiler and common language runtime (CLR) and then recursively searches object references to build a graph of what should be kept

Roots consist of:

  • Global/Static pointers. One way to make sure our objects are not garbage collected by keeping a reference to them in a static variable.
  • Pointers on the stack. We don’t want to throw away what our application’s threads still need in order to execute.
  • CPU register pointers. Anything in the managed heap that is pointed to by a memory address in the CPU should be preserved
    Each unneeded object (one that didn’t entered the graph will be erased and the objects will reform a new memory allocation. Each deletion is taking time so it’s better to minimize the amount of created objects.

    There are situations where the GC needs to execute code to clean up non-managed resources such as files, database connections, network connections, etc. One possible way to handle this is through a finalizer.

    class Sample

    {

               ~Sample()

                {

                             // FINALIZER: CLEAN UP HERE

                 }

    }

    What it does – inserts the object to a finalization queue , when GC sees that the object is no longer needed it inserts it into a freachable queue , and only after the finalizer is executed GC will approach to remove it. (at the next generation only) – so actually it’s prolonging the life of the object and maximize the usage of the heap memory , so it’s better to implement the finalizer when and only we really need it.

    A better practice is to be sure to clean up non-managed resources. As you can imagine, it is preferable to explicitly close connections and use the IDisposable interface for cleaning up instead of a finalizer where possible.

     

    public class ResourceUser : IDisposable

    {

                #region IDisposable Members

               public void Dispose()

               {

                             // CLEAN UP HERE!!!

               }

                 #endregion

    }

     

    If you implemented Dispose and used the using , at the end the Dispose will be executed and GC will know to clean up the unneeded resource.

    public static void DoSomething()

    {

             using (ResourceUser rec = new ResourceUser())

             {

                        // DO SOMETHING

               } // DISPOSE CALLED HERE

    }

    // DON’T ACCESS rec HERE

      Statics and heap overflowed

      1)If we use  a static member inside a static method , we better lock the initialization to prevent access to the same resource by different threads.

      class Counter

      {

      private static int s_Number = 0;

      public static int GetNextNumber()

      {

      lock (typeof(Counter))

      {

      int newNumber = s_Number;

      // DO SOME STUFF

      newNumber += 1;

      s_Number = newNumber;

      return newNumber;

      }

      }

      }

      The best approach with statics will be a singleton pattern

      public class Earth {

                  private static Earth _instance = new Earth();

                  private Earth() { }

                  public static Earth GetInstance() { return _instance; }

      }

       

      Summary of

      http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx

      This solution has been developed for Intranet and doesn’t take in concert security issues of Internet

      I got some client using the Windows Auth but the wcf could read the
      ServiceSecurityContext.Current.PrimaryIdentity

      So  I had to turn the Windows Auth for wcf also.

      The Wcf couldn’t show the services through the new Authentication until I didn’t change the mexHttpBinding to the basicHttpBinding

      Server Side :

      <bindings>
      <basicHttpBinding>
      <binding name="MyBasicHttp" allowCookies="true"
      maxReceivedMessageSize="2147483647"
      maxBufferPoolSize="2147483647"
      maxBufferSize="2147483647"
      openTimeout="10:00"
      >
      <readerQuotas maxDepth="2147483647" 
      maxStringContentLength="2147483647"
      maxArrayLength="2147483647"
      maxBytesPerRead="2147483647"
      maxNameTableCharCount="2147483647"/>

      <!--<security mode="TransportCredentialOnly">
      <security mode="TransportCredentialOnly">
      <transport clientCredentialType="Windows" />
      </security>-->
      </security>
      </binding>
      </basicHttpBinding>
      </bindings>
      .
      .
      .
      <services>
      <service name="Egged.Tnua.Wcf.ServiceImpl.EventService" 
      behaviorConfiguration="DefaultBehavior">
      <endpoint address="" 
      binding="basicHttpBinding" bindingConfiguration="MyBasicHttp"
      contract="My.Wcf.IServiceImpl.IEventService" />
      <!--<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />-->
      <endpoint address="mex" binding="basicHttpBinding" contract="IMetadataExchange" bindingConfiguration="MyBasicHttp" />
      </service>

       

      Client Side

        <system.serviceModel>
          <bindings>
            <basicHttpBinding>
              <binding name="BasicHttpBinding_IMyService"
                        openTimeout="00:10:00"
                         sendTimeout="00:10:00"
                        allowCookies="true"
                        bypassProxyOnLocal="false"
                        maxBufferPoolSize="200000000"
                        maxReceivedMessageSize="200000000">
                <security mode="TransportCredentialOnly">
                  <transport clientCredentialType="Windows" />
                </security>
              </binding>
      </basicHttpBinding>
          </bindings>
          <client>
       
            <endpoint address="http://localhost/MyWcfPublishedName/MyServiceEndpoint.svc"
                   binding="basicHttpBinding"
                   bindingConfiguration="BasicHttpBinding_IMyService"
                   contract="MyService.IMyService"
                  name="BasicHttpBinding_IMyService" />
      </client>   </system.serviceModel>

      Very important – in client in order that the binding would be activated on the endpoint you ought to add its name 

      to bindingConfiguration and Name

      It’s getting very importnat when there is a lot of data going through and the default binding just isn’t enough.

       

      When first published on server the Mvc has been Anonymous. then changed tio windows Authentixction caused 

      The resource cannot be found.

      The url has been the standart need one but – /login.aspx?ReturnUrl=%2fEgged.Tnua.TimeTable%2fHome

      The solution is : 

      adding the following lines to the AppSettings section of my web.config file in appSettings:

      <add key="autoFormsAuthentication" value="false" />
      <add key="enableSimpleMembership" value="false"/>

      Weirdly enough – solved the problem! 

      Found it here

      http://stackoverflow.com/questions/8205368/request-redirect-to-account-loginreturnurl-2f-since-mvc-3-install-on-server

      in cshtml : some scrollable - never mind the values - just for header freeze
        .Scrollable(s => s.Height(590))


       Catch with js and rebuild different from Kendo intentions

       .Events(e =>         {             e.DataBound("onDataBound");         }     )
      in css : delete other scrolls on the page
        html, body {
              overflow: hidden;
            
          }

      in js: in function onDataBound(e)

       $('.k-grid-content').height(window.innerHeight - 120);


      That's it . It should be Auto height by your screen container. (can play with the 120 to adjust)

      Tag Cloud

      Follow

      Get every new post delivered to your Inbox.