Tuesday, November 26, 2013

F# This expression is a function value, i.e. is missing arguments. Its type is List -> 'a -> List.

A common problem, when I refactor bigger chunks of F# code. This warning basically means that the indentation is incorrect. In my experience usually some parameters are not indented correctly. As an example:
let checkUrls = 
    Seq.fold (fun (acc:List) (x:string) -> 
        if (AsyncHttp(x) = HttpStatusCode.OK) then 
            (x :: acc) 
        else
            acc)
    []
    urls

In example above [] and URLs should be indented further then the call to the function, so it should look like a code below:
let checkUrls = 
    Seq.fold (fun (acc:List) (x:string) -> 
        if (AsyncHttp(x) = HttpStatusCode.OK) then 
            (x :: acc) 
        else
            acc)
        []
        urls

Monday, September 30, 2013

JavaScript style guides

There are various style guides available on a market for JavaScript. To name a few: For many years I was always suggesting to stick to Crockford convention, and use his book as a reference. But because people don't read books, and google style guide is much more explicite, and well defined, and available on the web with good examples. I decided to change my JavaScript style guide to google one.

Friday, September 27, 2013

Hacker News London meetup

I haven't keep a track of tech meetings I attended recently. Maybe it would be good to start doing it again:
Hacker news meetup a good one. I really enjoyed people, presentations, beer and pizza. Maybe not including the last presentation (google app engine), because it was to commercial, and nothing interesting was said. The sad part is it was at this same time as Sitecore User Group meeting, that I usually attend.

Friday, September 20, 2013

JQuery $(...).ready is not a function


This one happened to me many times. It usually means that some script override the $ variable, and after JQuery has been initialized. In other words there is a huge chance that one of a javascript libraries that you added recently overrides $. The best way to check if it's the case is to fire up following script under firebug script console.
alert($)

If the result is simmilar to this:
function (a,b){return new e.fn.init(a,b,h)}

Everything is ok, this is how $ looks when JQuery is in charge of it. But often I see something else. For example a code below means that mootools is also used and it takes over $ function:
function (B, C) { if (B && B.$family && B.uid) { return B; } var A = $type(B); return ($[A]) ? $[A](B, C, this.document) : null; }

And it means that some code did something nasty with $ variable. The next thing that I do is to read libraries, disable them, and follow a typical tracing path.

Monday, September 16, 2013

What to do if there is no FireBug installed in Firefox


I noticed that many Firefox users are unaware that since version 11 firefox introduced a tool that is similar to firebug. You can trigger it by hitting:
Shift+F7

I sometimes debug/trace an issue not from a development machine, and I don't have an access to firebug, so it is worth to remember, that Style Editor is there to help you.

Thursday, August 8, 2013

Proxy Ignore List for IE (ProxyOverride)

It is really easy to ignore proxy for a specific URL under Firefox.

You simply go to:
 Tools->Options->Advanced->Network->Connection Settings 
and add url to No Proxy list.
There is no such inteface for IE or Chrome. In order to add URL to ignore list you need to modify registry:
HKEY_USERS\[UserID]\Software\Microsoft\Windows\CurrentVersion\Internet Settings

And add your entry to ProxyOverride list.

Thursday, July 25, 2013

SetSite failed for package [Microsoft.VisualStudio.Editor.Implementation.EditorPackage]



After the 07/10/2013 Microsoft update, VS 2012 doesn't want to work. It throws exceptions that can be visible under:
C:\Users\[user]\AppData\Roaming\Microsoft\VisualStudio\11.0\ActivityLog.xml

In order to fix the issue one needs to clear the VS cache under:
%LOCALAPPDATA%\Microsoft\VisualStudio\11.0\ComponentModelCache

Decimal and Double once again

Yesterday I had a discussion with my co-worker about primitive types, I suggested that he should use decimal instead of double otherwise results of his computation may be misleading/incorrect. It is a booking applications and showing a correct prize (fee, cost) is crucial. His argument was that: "Double is a floating point type and decimal is not, that's why precision kept in double is bigger and it is safer to use it". Majority of information mentioned in a sentence above is not true! Decimal is also a floating point type, but with a base 10 not 2 like double has. First have a look at floating point canonical equation taken from wikipedia:


It explains what exponent and mantissa is. Because double and decimal have a fixed size in computer memory in C# language, designers had to decide how many bits should be spent on matissa and how many for exponent. And as for C# language it is illustrated below:
A double represents a number of the form +/- (1 + F / 252 ) x 2E-1023, where F is a 52 bit unsigned integer and E is an 11 bit unsigned integer; that makes 63 bits and the remaining bit is the sign, zero for positive, one for negative.

A decimal represents a number in the form +/- V / 10X where V is a 96 bit unsigned integer and X is an integer between 0 and 28.

It all means that decimal is much safer in doing a correct computations than double.

Wednesday, July 17, 2013

NHibernate cascade save and how many queries are produced

The simplest configuration for a cascade save in nhibernate looks following.
public class CUrlMap : ClassMap<CUrl>
{
    public CUrlMap()
    {
        Table("CommonUrl");
        Id(x => x.Id);
        Map(x => x.CommonUrl);

        HasMany(x => x.CMarketUrls)
            .Inverse()
            .Cascade.All()
            .KeyColumns.Add("CommonUrlId");
    }
}

public class CMarketUrlMap : ClassMap<CMarketUrl>
{
    public CMarketUrlMap()
    {
        Table("CommonMarketUrl");
        Id(x => x.Id);
        Map(x => x.MarketUrl);
        Map(x => x.MarketId);

        References(x => x.CUrl).Column("CommonUrlId");
    }
}

One CUrl has many CMarketUrls. The goal is to create/update/delete everything in lowest possible number of steps. Unfortunately it is not really beautiful from a code and SQL point of view.
The simple code to save CUrl
using (var trans = _repository.BeginTransaction())
{
    _repository.SaveOrUpdate(curl);
    trans.Commit();
}

The first thing is that CommonUrlId column (a foreign key) in SQL must allowed nulls. It is because what Nhibernate does during creation of CUrl is it first creates it and then it creates all CMarketUrl that it keeps in a collection (CMarketUrls). It means that total number of queries is:
  • 1 x insert to CUrl
  • K x insert to CMarketUrls (where K is number of CMarketUrl that are kept in CMarketUrls)

But we are not done yet, the code listed above will save everything but it will not assign Id from a freshly created CUrl to also freshly created CUrlMaps. Programmer needs to map this Id manually during creation. It complicates code, and now it looks:
using (var trans = _repository.BeginTransaction())
{
    _repository.SaveOrUpdate(curl);
                    
    foreach (var cMarketUrl in curl.CMarketUrls)
    {
        cMarketUrl.CUrl = curl;
        _repository.SaveOrUpdate(cMarketUrl);
    }
    trans.Commit();
}

What nhibernate will do is after creation of new records it will update CMarketUrls and set to them newly created Id for CUrl.

It all means that each time when we create a new CUrl with some CMarketUrls the total number of queries is following:
  • 1 x insert to CUrl
  • K x insert to CMarketUrls (where K is number of CMarketUrl that are kept in CMarketUrls)
  • 1 x batch update (in this one batch all CMarketUrls are updated, CUrl is set to them)

As always there is plenty of place to improve nhibernate.

Wednesday, June 19, 2013

Assembly bind failure logging (Fusion) in .NET

The Assembly Binding Log Viewer displays details for failed assembly binds. This information helps you diagnose why the .NET Framework cannot locate an assembly at run time. These failures are usually the result of an assembly deployed to the wrong location or a mismatch in version numbers or cultures. The common language runtime's failure to locate an assembly typically shows up as a TypeLoadException in your application. I use information in this log really often, and I always struggle to find this article of how to configure it. And the steps are:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
Add:
DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
String LogPath set value to folder for logs (e.g. C:\FusionLog\)

I have to restart my machine before I see results.

Tuesday, June 18, 2013

Disk Usage (QueueLenght) monitoring - why my machine is not responding if CPU and Memory is doing good.

For a last year I saw many times that it is not CPU or Memory that is stopping system from responding quickly, it is hard drive that is the weakest link. A typical QueueLength (number of processes waiting for HD resource) should be around 0.05 or better 0.01 as illustrated below. (In order to see this screen hit open Windows Task Manager (ctr+shift+Esc)-> performance->Resource Monitor->Disk).

But if there are many processes trying to write on hd this diagram looks like this:

It means that HD is a major bottle neck in a system.

Thursday, June 13, 2013

Just Time for .NET

I need to represent just time in .NET, no date. My scenario is that I have a scheduler and I want to run a job 4 times a day at specific hour: 4:00, 10:00, 16:00, 22:00. There is no default data type in .NET to represent this kind of information. DateTime requests from me setting a Date (which is irrelevant in my scenario), and also the simplest DateTime constructor that uses hour also requests from me setting minutes and seconds, which again are irrelevant for me. The simplest constructor using DateTime looks like:
new DateTime(year:1, month:1, day:1, hour:4, minute:0, second:0);

If I try to parse a date from a string and I pass just time a date is set by default to "01/01/01" and I find it silly.
I can use TimeSpan, but this data type was design to keep a span of a time, not a point of a time, and it is really misleading.
The approach I took is to install NodaTime and there is a nuget package. Inside NodaTime there is a class called Period that is meant to represent exactly what I need a period in time. Constructor that I used is listed below.
Period.FromHours(4);

Wednesday, June 5, 2013

ASP.NET strongly typed repeater

Today, I looked at old ASP.NET code, and saw something like this:
<asp:Repeater runat="server" ID="repTourDepartureCache" >
    <ItemTemplate>
        <tr>
            <td>
                <%# Eval("Key") %>
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

The problem is that the binding done here is done by so called "magic string". And if someone will change a property name from "Key" to something else this code will stop working. Programmer writing this code was not aware that in .NET 4.5 strongly typed data binding was introduced by using additional attribute ItemType. The above code should look:
<asp:Repeater runat="server" ID="repTourDepartureCache" ItemType="TTC.TT.Entities.ViewModels.PrettyPrintedTourDeparture">
    <ItemTemplate>
        <tr>
            <td>
                <%# Item.Key %>
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

There is a full Intellisense support for this kind of binding. And it makes refactoring easier. For generic types ItemType definition looks like:
<asp:Repeater runat="server" ID="repTourDepartureCache" ItemType="System.Collections.Generic.KeyValuePair`2[System.String, System.String]">
</asp:Repeater>

Tuesday, May 28, 2013

MSBuild Publish target for LocalEnvironment configuration (why BeforePublish and AfterPublish was not triggered)


The best way to debug msbuild, or to find what targets and tasks are triggered, and where can you hook up, is to ask msbuild to be more verbose (under VS tools->options).

After looking at what targets are executed when publishing application from within VS by using Local Environment as a publish method, one can see that BeforePublish and AfterPublish was never triggered. But you can start using any target that you can see in log to do desired operation. For example, if I want to do something after CompileWebSite target is finished running I just write something like:
<Target Name="CopyToDeployFolder" DependsOnTargets="CompileWebSite">
    <Exec Command="xcopy.exe  $(OutputDirectory) $(DeploymentDirectory) /e" WorkingDirectory="C:\Windows\" />
</Target>

Namedoesn't matter, it is DependsOnTargets that is important.

IIS Access denied problem


Access denied problem is a most typical problem for me when setting new application under IIS. The most typical example that I see recently in various environments is related to understanding of what users accounts are used under a hood. Namely that sometimes there is a need to assign permissions on a hard drive not for one user but for two of them.

Consider that you set up application pool identity to Network Service, it is a common mistake to believe that this is the only user that you need to grant a permission to application folder. Unfortunately if application allowed anonymous users, they also run in a context of a user account, and by default in IIS 7.5 it is set to IUSR account. It means that you need to set up permissions also for this user on a hard drive.

Monday, May 20, 2013

Tuesday, March 12, 2013

Disable sitecore cahe

To tern off sitecore caching set following values in sitecore config.
<!--  CACHING ENABLED
 Determines if caching should be enabled at all
 Specify 'true' to enable caching and 'false' to disable all caching
-->
<setting name="Caching.Enabled" value="false" />
<!--  DISABLE BROWSER CACHING
 If true, all pages will have:
   Cache-Control: no-cache, no-store
   Pragma: no-cache
 in the http header
-->
<setting name="DisableBrowserCaching" value="true" />

Monday, March 11, 2013

MSBuild copying all files in folder to destination folder

Typical task as for me, after build I want to copy some files from one location to other. All files that exist in folder. The not working approach looks like:
I would think that it should work, but it doesn't
<Target Name="AfterBuild">
<Copy SourceFiles="Foo\*.*" DestinationFolder="$(OutputPath)" ContinueOnError="true" />
</Target>
The working solution is below
<ItemGroup>
    <_CopyDeployableAssemblies Include="Foo\*.*" />
</ItemGroup>
<Target Name="AfterBuild">
<Copy SourceFiles="@(_CopyDeployableAssemblies)" DestinationFolder="$(OutputPath)" ContinueOnError="true" />
</Target>
It will copy all files from folder Foo to Bin folder.

Sunday, March 10, 2013

Connecting lm298n with arduino


The connection is really strait forward. From arduino pins 6,7,5,4 connect accordingly to inputs IN1, IN2, IN3, IN4 in lm298n. And that's it, it will work. In terms of power supply, there are 2 power inputs in lm298n (5V, VCC), 5V can be connected to arduino, but if your motor requires more power, then you need to connect additional power supply to VCC. It is a really good practice to connect all GND cable together, I mean from additional power supply and from arduino. A code below increase a speed of two motors connected to lm298n and then decrease it.

I started recently my new mobile robotics project, and a picture shows a mobile framework connected to lm298n and arduino.
// Initialize
int PWM1   = 6; // PWM Pin Motor 1
int PoM1 = 7;   // Polarity Pin Motor 1
int PWM2   = 5; // PWM Pin Motor 2  
int PoM2 = 4;   // Polarity Pin Motor 2
 
int ValM1   = 0; // Initial Value for PWM Motor 1 
int ValM2   = 0; // Initial Value for PWM Motor 2
 
int i = 25;     // increment
// Used to detect acceleration or deceleration
boolean goUp = true ; 
 
void setup() 
{
  pinMode(PWM1,   OUTPUT); 
  pinMode(PoM1,   OUTPUT); 
  pinMode(PWM2, OUTPUT);   
  pinMode(PoM2, OUTPUT);   
  digitalWrite(PoM1, LOW) ;   // Both motor with same polarity
  digitalWrite(PoM2, LOW) ;
  analogWrite(PWM1, ValM1);   // Stop both motors => ValMx = 0
  analogWrite(PWM2, ValM2);    
  Serial.begin(9600);         // Used to check value 
}
 
// Main program
void loop()
{
  // give some time to the motor to adapt to new value
  delay (500) ;               
  if ((ValM1  < 250) && goUp) // First phase of acceleration
  {
      ValM1 = ValM1 + i ;     // increase PWM value => Acceleration
      ValM2 = ValM2 + i ;      
  }
  else
  {
    goUp = false ;            // Acceleration completed
    ValM1 = ValM1 - i ;       // Decrease PWM => deceleration
    ValM2 = ValM2 - i ;   
    // My motor made fanzy noise below 70  
    if (ValM1  < 75)           
    {                         // One below 75, I set to 0 = STOP
       ValM1 = 0 ;
       ValM2 = 0 ;
       goUp = true ;          // deceleration completed
    }
  }
  // If PWM values are OK, I send to motor controller
  if ((ValM1 > 75) && (ValM1 < 255))  
  {
    analogWrite(PWM1, ValM1);  
    analogWrite(PWM2, ValM2);
  }  
  Serial.print(ValM1);        // Debug. Print Value Motor 1
  Serial.print("\t");         // Print tab
  Serial.println(ValM2);      // Print Value Motor 2 to Serial
}
// End.

Wednesday, March 6, 2013

Reseting admin password in Sitecore

Sitecore inside Core db stores users information. In order to reset password to 'b' for a user 'admin' one has to run a following script
UPDATE [aspnet_Membership] SET Password='8dC23rEIsvuttG3Np1L4hJmJAOA=', PasswordSalt=' joeLPwcwMq6L7kyuVfVS7g=='   
WHERE UserId IN (SELECT UserId FROM [aspnet_Users] WHERE UserName = 'sitecore\Admin') 
It is important to set both Password and PasswordSalt.

Monday, February 25, 2013

Cloning objects in .NET

In .NET I want to do something like:
// This is illegal in C#
public class PdfDetails : ICloneable<PdfDetails>
{
    public int Id { get; set; }
    public string FileName { get; set; }

    public PdfDetails Clone()
    {
        return MemberwiseClone();
    }
}
But I can't because IClonable is not a generic interface. I remember reading explanation for it in Skeets book or Eric Lipper blog, and it was because in .NET framework before 2.0 there was no generics and since then some of the old interfaces were replaced with generic once, in other cases new generics interfaces were created, and in some cases nothing happened - and ICloneable is an example of this group, there is no support or replacement for generics. So I need to do something like:
public class PdfDetails : ICloneable
{
    public int Id { get; set; }
    public string FileName { get; set; }

    public object Clone()
    {
        return MemberwiseClone();
    }
}
Unfortunately I do not want to return an object type I want to return a PdfDetails type but I can't do it with a non generic interface. So I need to do overloading to create a method that returns a PdfDetails type, the thing that I am really thinking of is something like:
public class PdfDetails : ICloneable
{
    public int Id { get; set; }
    public string FileName { get; set; }

    public object Clone()
    {
        return MemberwiseClone();
    }

    // This is illegal in C#
    public PdfDetails Clone()
    {
     return (PdfDetails) Clone();
    }
}
But I can't do it in C#, because it is not how overloading works here. So I need to do something like:
public class PdfDetails : ICloneable
{
    public int Id { get; set; }
    public string FileName { get; set; }

    // unfortunately this method can not be public
    object ICloneable.Clone()
    {
       return MemberwiseClone();
    }

    public PdfDetails Clone()
    {
        // because ICloneable.Clone() can not be public I can not call it from here
        // instad I need to call again MemberwiseClone() method
        return (PdfDetails)MemberwiseClone();
    }
}
But when you look at the code above you ask a question then why do I really want to implement a ICloneable interface in first place. And I belive, that you don't have to if you don't need to. What I mean is you can go and safely write a code like:
public class PdfDetails 
{
    public int Id { get; set; }
    public string FileName { get; set; }

    public PdfDetails Clone()
    {
        return (PdfDetails)MemberwiseClone();
    }
}
It does the job, but it doesn't inform other programmers that PdfDetails class is supposed to Clone objects. That's why I enjoy writing my own interface:
public interface ICloneable<out T>
{
    T Clone();
}
And than implement it
public class PdfDetails : ICloneable<PdfDetails>
{
    public PdfDetails Clone()
    {
 return (PdfDetails)MemberwiseClone();
    }
}

Thursday, February 14, 2013

How ASP.NET lifecycle works

Today I had to explain it to few people, so I thought that it would be good to have a place to write it down, so I don't need to do it next time:)

Global.asax.cs includes a class (usually called Global) that inherits from HttpApplication. The hard part is that HttpApplication can only handle one request per time. The confusing part is that this class includes methods that should be executed just once per application lifecycle, and if HttpApplication is able to handle only one request per time, how is it possible that everything works, and how is it possible that IIS is able to handle multiple requests pert time?

First things first, methods like Application_Start, Application_End are called once per AppDomain lifecycle, programmer should not be concerned that they exist in a scope of a class (usually called Global) that can be created many times. So these methods are different than for example modules that are executed once per HttpApplication. And it leads us to a second thought, class that exists in Global.asax (usually called Global) should be treated as an ordinary class, it means that its object can be created and destroyed at any time.

When a new request is send to IIS, and Global class object is busy handling other request, IIS can create a new thread and create a new instance of Global class. IIS can create such thread, but doesn't have to, it can stack a request and wait to reuse Global object that will finish handling previous requests.

To make it even more complicated each AppDomain that was created by ASP.NET can have multiple Global objects, so it is extremely easy to 'configure' something wrong, especially when you use static keyword, or a singleton pattern! Now it is also important to notice that one application can run as many AppDomains, but it is not very useful configuration (in majority of cases), but one IIS can host multiple applications, and each of them 'should' run in a separate AppDomain.

Hope it clarifies something :)

Thursday, January 24, 2013

SQL Server installation Unknown error (0xfffffff)

I’ve seen this problem so many times. The hard part is that the error is not meaningful, and there is no additional info in EventViewer or SQL installation logs. The problem is GPO policy. Basically someone set a policy for AD not to allowed users to run applications called
setup.exe
You need to disable it in regedit tool, goto:
\HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun
And rename setup.exe to something like setupzzz.exe

No IIS manager after adding IIS role to Microsoft Server 2008 R2

For some weird reasons sometimes when I add IIS role to Microsoft Server 2008, IIS Manager is not installed automatically. It needs to be installed by adding IIS Management Console Service Role.

Tuesday, January 22, 2013

IIS 7.5 application path for web.config problem

A very interesting error is displayed when selecting a WebSite and trying to set its configuration under IIS. If you select a Site under IIS Manager, you should be able to modify configuration from within IIS Manager. For example by selecting 'Error Pages'. But when I tried to click on any of configuration Icons I received a following message: There was an error while performing this operation. Filename: \\?\C:\inetpub\web.config
It was weird because the path for web.config was correct, and IIS process had permissions to access application folder and web.config itself. The error was not meaningful at all. The problem was resolved after installing 'HTTP Redirections' Role Services for IIS.
I had to reboot my machine after that.

In an addition one needs to install a third party software called URL Rewrite (I installed version 2.0) using microsoft platform installer.

My understanding is that IIS Manager w/o some features from HTTP Redirections was unable to parse web.config correctly, and it was raising a weird exception.

Howto Register (copy) a dll in GAC under Server 2008 R2 w/o installing additional software

It was a pain. There is plenty of information in the web, but they do not target Server 2008 R2, or require installation of VS or .NET Framework 2.0 Software Development Kit (SDK). First let me just point out that gacutil when you run a command:
gacutil /i yourdll.dll
Will just copy a dll to GAC folder, so you can do it manually without gacutil, if you know how.

When you try to drag and drop a dll from one folder to GAC folder you receive a message 'Access is denied' (as in screen), or nothing seems to happen (depending on a configuration). To copy dll to GAC you need to turn off UAC (User Account Control - a thing that blocs you from doing something interesting under Server 2008) you need to:
Start->Control Panel->User Accounts->User Accounts->Change User Account Control settings

And set it to 'Never notify' (as in screen). You need to restart your machine.

After you restart it you will be able to grab and drop from any window to GAC folder.

Friday, January 18, 2013

The decimal type problem in financial word

Decimal is a typical type used in financial word, to prevent lost of information/precision during mathematical computations. There is one issue that is not put in a consideration. The C# ECMA specification guarantees that the following types will be written atomically: reference types, bool, char, byte, sbyte, short, ushort, uint, int and float. There is no decimal on that list. It means that:
class AtomicityExample {
    decimal _value;
    void SetValue(decimal value) {_value = value;}
    decimal GetValue() {return _value;}
}
If the code is executed by many threads, the returned value of GetValue method may be not a value that was set by a SetValue.

What is even less know is that the order of the operations in C# may change, due to .net optimization. Consider following code:
class OrderExample {
    decimal d1;
    volatile decimal d2;
    decimal d3;

    void Assign(){
        d1 = 1;
        d2 = 2;
        d3 = 3;
    }
}
The assignment in a code above can happen in following ways:
d1 = 1;
d2 = 2;
d3 = 3;
or
d1 = 1;
d3 = 3;
d2 = 2;
or
d3 = 3;
d1 = 1;
d2 = 2;
In other words volatile variable can be assigned only after d1 was assigned, but when exactly depends on a compiler. Be aware that majority of programmers don't even use volatile keyword, and without volatile keyword reads/writes of variables above can happen in any order. And it matters, because I've seen so many times a code that looked like:
class FalseSecurityExample {
    decimal d1;
    bool assigned;

    void Assign(){
        d1 = 1;
        assigned = true;
    }

    decimal Calculate(){
        if(assigned){
            return d1;
        }
    }
}
It means that in an example above d1 may not be set before it is returned, and if you add to a consideration fact that decimal is not atomic, you can expect anything to be returned by this code.

When I ask people why do they write such code, and if they are aware of issues that are illustrated above, usually they answer, that we are not writing a project for NASA, or anything like that so bug off. Interesting.

Wednesday, January 16, 2013

Disabling proxy under IE

It's easy under Firefox and Chrome, but somehow there is no option for that in IE. To turn it off, search your Registry (inside Regedit) for ProxyEnable, and set its value to 0, on my computer I found 4 matching places, and I changed all of them. Done. The hard part is that I have to do it from time to time, it means that for some reasons some process set the ProxyEnable to 1 sometime (once in month).

Monday, January 14, 2013

Application recycling

For some time I was worried about unknown behaviour of my application. By analysing perfmon logs showing memory counters of iis processes and perfmon logs for operating system basic counters, I could clearly see that something bad is going on from time to time. Basically it looks like my application was being restarted. By looking at counters it looks like there is a memory leak in app (this is a very old app, and no one knows how it really works). The thing that I did not understand was why it is restarted, or what magic clears entire memory of app. Because I do not have an access to a production it was really hard to guess by looking at few perfmon logs. The next thing that I did not understand was why there was no error or warning in a log file (or event log in OS). As an addition my failover architecture was never triggered. Failover is set up to use a loadbalancer to ping my app and if it's not able to receive a response it redirects traffic to a different server. Finally it enlightens me that by default IIS is set up to recycle app every 1740 minutes (about 29 hours). When recycling happens, a new process is created in a background to handle new requests, and an old process is allowed to finish dealing with request that he was requested to deal with, before it is terminated – that’s why app is constantly responsive. As always the simplest answer is the hardest to think of.

Saturday, January 12, 2013

Arduino Servo controling

There is a huge buzz about how to control servo from arduino in the net. Just to let people know what is a simplest solution. But first few details about servo and arduino. Servo comes with 3 cables with 3 different colors:
  • brown - needs to be connected to ground
  • red - needs to be connected to power supply +5V
  • orange - needs to be connected to control pin - thru this you will send commands to servo from arduino library.
So let's say that you connected everything as described above, and orange (data) cable is connected to a pin 5. Below is a simple code that rotates a servo waits 2s and rotates it to a different position.
#include 

Servo servoh;
int runOnce = 1;

void setup() {
  servoh.attach(5);
}

void loop() {
  if(runOnce == 1){
    servoh.write(10);
    runOnce = 0;
  }else{
    servoh.write(90);
    runOnce = 1;
  }
  
  delay(2000);
}

Thursday, January 3, 2013

Reading from transaction log file - SQL Server

Sometimes I need to figure out when a certain operation happened, like when a row was deleted, or added. In order to investigate I use two tools:
DBCC LOG(databasename, typeofoutput)

where typeofoutput:
0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.
fn_dblog runs in a context of a DB, so be sure to select the one that is interested to you. Results are ordered, the oldest are first to be displayed.
SELECT
SPID,                         -- The process ID for the transaction
[Begin Time],                 -- The start time for the transaction
[Current LSN],                -- The lsn of this record           
[Previous LSN],               -- Previous lsn for this record
Operation,                    -- The operation performed by the log record
Context,                      -- The resource affected by the operation
[Log Reserve],                -- The space reserved for rollback in bytes
AllocUnitName,                -- The name a the affected allocation unit
[Page ID],                    -- The page ID of the affected page
[Number of Locks],            -- The number of locks held by the transaction
[Lock Information]            -- Information about the locks held and the resources locked
FROM fn_dblog(NULL, NULL)
The number of rows displayed depends on a Recovery Mode, if it's set to Simple, SQL server will decide how much information keep in transaction log file, if it's set to FULL, then this query will display all operations from a time when Recovery Mode was set to FULL.