Monday, May 07, 2012

GC KeepAlive method–what it really does

Quite useful, I was missing this corner..
Below is quote from documentation as it is provided by code author.



// This method DOES NOT DO ANYTHING in and of itself.  It's used to
// prevent a finalizable object from losing any outstanding references
// a touch too early. The JIT is very aggressive about keeping an
// object's lifetime to as small a window as possible, to the point
// where a 'this' pointer isn't considered live in an instance method
// unless you read a value from the instance. So for finalizable
// objects that store a handle or pointer and provide a finalizer that
// cleans them up, this can cause subtle ----s with the finalizer
// thread. This isn't just about handles - it can happen with just
// about any finalizable resource.
//
// Users should insert a call to this method near the end of a
// method where they must keep an object alive for the duration of that
// method, up until this method is called. Here is an example:
//
// "...all you really need is one object with a Finalize method, and a
// second object with a Close/Dispose/Done method. Such as the following
// contrived example:
//
// class Foo {
// Stream stream = ...;
// protected void Finalize() { stream.Close(); }
// void Problem() { stream.MethodThatSpansGCs(); }
// static void Main() { new Foo().Problem(); }
// }
//
//
// In this code, Foo will be finalized in the middle of
// stream.MethodThatSpansGCs, thus closing a stream still in use."
//
// If we insert a call to GC.KeepAlive(this) at the end of Problem(), then
// Foo doesn't get finalized and the stream says open.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void KeepAlive(Object obj);

Sunday, April 08, 2012

Get user name in SQL

… without domain:

SELECT PARSENAME(REPLACE(ORIGINAL_LOGIN(), '\', '.'), 1)

Currencies having stocks quoted in cents

I think this is exhaustive list for now:

BWp Botswana Pula
GBp British Pound
ILs Israeli Shekel
KWd Kuwaiti Dinar
MWk Malawian Kwacha
SZl Swaziland Lilangeni
ZAr South African Rand

“267: The directory name is invalid” error when running via runas command

Should be one of:

  • User Access Control settings prevent you from executing a program
  • Directory has no access for user which is specified in runas
  • You shared your folder and that reset user rights on the folder –
    go to Properties->Security and add runas user..

Monday, January 02, 2012

SQL–how to find nth row / nth order element

Example below is self-explanatory – you should assign rank by desirable criteria and then just group by your categories (product id and name is sample below), selecting only entries of certain rank. In sample below you would select all entries with second biggest ID per category.

CREATE TABLE  #test ( id int, ProductName VARCHAR(25) )
insert into #test
select 1, 'Apple' union all
select 2, 'Apple' union all
select 5, 'Apple' union all
select 3, 'Orange' union all
select 4, 'Orange' union all
select 10, 'Orange'
SELECT * FROM #test

SELECT maxID FROM
(
    SELECT MAX(id) AS maxID, ProductName AS nn, RANK() OVER (PARTITION BY ProductName ORDER BY id DESC) AS MyRank
    FROM #test
    GROUP BY id, ProductName
) tmp
WHERE tmp.MyRank = 2

Get current username in SQL

SELECT PARSENAME(REPLACE(ORIGINAL_LOGIN(), '\', '.'), 1)

Tuesday, October 11, 2011

What is a size of DateTime type in C#?

What is a size of DateTime type in C#? - A trivial question, unexcitingly facing few obstacles. Self-explanatory code below describes how you can't get it and how you can (and yes, it's 8 bytes):
using System;

namespace DateTimeSizeExample
{
  public struct TypeSizeProxy<T>
  {
    public T PublicField;
  }

  public static class SizeCalculator
  {
    public static int SizeOf<T>()
    {
    try
    {
      return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
    }
    catch (ArgumentException)
    {
      return System.Runtime.InteropServices.Marshal.SizeOf(new TypeSizeProxy<T>());
    }
  }

  public static int GetSize(this object obj)
  {
    return System.Runtime.InteropServices.Marshal.SizeOf(obj);
  }
}

internal class Program
{
private static void Main(string[] args)
{
// Error: 'System.DateTime' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// (consider using System.Runtime.InteropServices.Marshal.SizeOf)
//int s1 = sizeof(DateTime);

// Run time Argument Exception: Type 'System.DateTime' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed
//int s2 = System.Runtime.InteropServices.Marshal.SizeOf(typeof(DateTime));

int dateTimeSize = SizeCalculator.SizeOf<DateTime>(); // 8 bytes
}
}
}