Wednesday, December 23, 2009

Flatten array of arrays using linq

If you have list of object that contains list of other objects and you want to collect all children in one list linq can make it simple. For example:


List<int> listOfInt = new List<int>();
List<List<int>> listOfListOfInts = new List<List<int>>();
foreach (List<int> ints in listOfListOfInts)
{
foreach (int i in ints)
{
listOfInt.Add(i);
}
}


but using linq the following statements become:


List<int> listOfInt = listOfListOfInts.SelectMany(ints => ints).ToList();

Thursday, December 17, 2009

"Missing XML comment..." in service reference file

When I added service reference in my project I have got a lot of "Missing XML comment for public visible type..." warning messages in Reference.cs file. Those warnings didn't allow me to see real important warning messages. To disable this, add:


#pragma warning disable 1591


at the beginning of Reference.cs file and


#pragma warning restore 1591


at the end of Resource.cs file.

And off course you will need to add this every time you update reference.

Use svn revision number for assembly version

If you want to use svn revision number as revision number of assembly version this post can be helpful.
I have used information from http://carlosrivero.com/add-svn-revision-macro-for-visual-studio-2005-2008 and http://stackoverflow.com/questions/1157485/whats-regular-expression-for-update-assembly-build-number-in-assemblyinfo-cs-fil to create macro for this.

Here is the macro:



Public Sub UpdateRevisionNumber()


        Dim proj As Project


        Dim objProj As Object()


        objProj = DTE.ActiveSolutionProjects


 


        If objProj.Length = 0 Then


            Exit Sub


        End If


        proj = DTE.ActiveSolutionProjects(0) 'gets the path of the web project to write to the web.config


        Dim x As String = proj.ProjectItems.ContainingProject.FullName


 


        Dim p As New System.Diagnostics.Process


        'first update the root to get the latest revision


        p.StartInfo.UseShellExecute = False


        p.StartInfo.RedirectStandardOutput = True


        p.StartInfo.RedirectStandardError = True


        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden


        p.StartInfo.FileName = "svn.exe"


        p.StartInfo.WorkingDirectory = proj.Properties.Item("FullPath").Value()


        p.StartInfo.Arguments = "info"


        p.Start()


        Dim strerror As String = p.StandardError().ReadToEnd()


        Dim output As String = p.StandardOutput().ReadToEnd()


        p.WaitForExit()


        'get the revision


        Dim re As New Regex("Revision:\s+(\d+)\s*")


        Dim ver As String


        ver = re.Match(output).Groups(1).Value


        'add one so the number is not one revision behind


        Dim version As Integer


        version = Convert.ToInt32(ver) + 1


 


        Dim propPath As String


        propPath = proj.Properties.Item("FullPath").Value() + "Properties\AssemblyInfo.cs"


 


        Dim globalAssemblyContent As String = File.ReadAllText(propPath)


        Dim rVersionAttribute As Regex = New Regex("\[[\s]*(\/\*[\s\S]*?\*\/)?[\s]*assembly[\s]*(\/\*[\s\S]*?\*\/)?[\s]*:[\s]*(\/\*[\s\S]*?\*\/)?[\s]*AssemblyVersion[\s]*(\/\*[\s\S]*?\*\/)?[\s]*\([\s]*(\/\*[\s\S]*?\*\/)?[\s]*\""([0-9]+)\.([0-9]+)(.([0-9]+))?(.([0-9]+))?\""[\s]*(\/\*[\s\S]*?\*\/)?[\s]*\)[\s]*(\/\*[\s\S]*?\*\/)?[\s]*\]")


        Dim rVersionInfoAttribute As Regex = New Regex("\[[\s]*(\/\*[\s\S]*?\*\/)?[\s]*assembly[\s]*(\/\*[\s\S]*?\*\/)?[\s]*:[\s]*(\/\*[\s\S]*?\*\/)?[\s]*AssemblyFileVersion[\s]*(\/\*[\s\S]*?\*\/)?[\s]*\([\s]*(\/\*[\s\S]*?\*\/)?[\s]*\""([0-9]+)\.([0-9]+)(.([0-9]+))?(.([0-9]+))?\""[\s]*(\/\*[\s\S]*?\*\/)?[\s]*\)[\s]*(\/\*[\s\S]*?\*\/)?[\s]*\]")


 


        'Find Version Attribute for Updating Build Number


        Dim mVersionAttributes As MatchCollection = rVersionAttribute.Matches(globalAssemblyContent)


        Dim mVersionAttribute As Match = GetFirstUnCommentedMatch(mVersionAttributes, globalAssemblyContent)


        Dim gBuildNumber As Group = mVersionAttribute.Groups(11)


        Dim newBuildNumber As String


 


        'Replace Version Attribute for Updating Build Number


        If (gBuildNumber.Success) Then


            newBuildNumber = version.ToString()


            globalAssemblyContent = globalAssemblyContent.Substring(0, gBuildNumber.Index) + newBuildNumber + globalAssemblyContent.Substring(gBuildNumber.Index + gBuildNumber.Length)


        End If


 


        'Find Version Info Attribute for Updating Build Number


        Dim mVersionInfoAttributes As MatchCollection = rVersionInfoAttribute.Matches(globalAssemblyContent)


        Dim mVersionInfoAttribute As Match = GetFirstUnCommentedMatch(mVersionInfoAttributes, globalAssemblyContent)


        Dim gBuildNumber2 As Group = mVersionInfoAttribute.Groups(11)


 


        'Replace AssemblyFileVersion


        If (gBuildNumber2.Success) Then


            If String.IsNullOrEmpty(newBuildNumber) Then


                newBuildNumber = version.ToString()


            End If


 


            globalAssemblyContent = globalAssemblyContent.Substring(0, gBuildNumber2.Index) + newBuildNumber + globalAssemblyContent.Substring(gBuildNumber2.Index + gBuildNumber2.Length)


        End If


 


        File.WriteAllText(propPath, globalAssemblyContent)


    End Sub


 


 


    Private Function GetFirstUnCommentedMatch(ByRef mc As MatchCollection, ByVal content As String) As Match


        Dim rSingleLineComment As Regex = New Regex("\/\/.*$")


        Dim rMultiLineComment As Regex = New Regex("\/\*[\s\S]*?\*\/")


 


        Dim mSingleLineComments As MatchCollection = rSingleLineComment.Matches(content)


        Dim mMultiLineComments As MatchCollection = rMultiLineComment.Matches(content)


 


        For Each m As Match In mc


            If m.Success Then


                For Each singleLine As Match In mSingleLineComments


                    If singleLine.Success Then


                        If m.Index >= singleLine.Index And m.Index + m.Length <= singleLine.Index + singleLine.Length Then


                            GoTo NextAttribute


                        End If


                    End If


                Next


 


                For Each multiLine As Match In mMultiLineComments


                    If multiLine.Success Then


                        If m.Index >= multiLine.Index And m.Index + m.Length <= multiLine.Index + multiLine.Length Then


                            GoTo NextAttribute


                        End If


                    End If


                Next


 


                Return m


            End If


NextAttribute:


        Next


 


        Return Nothing


 


    End Function


Monday, November 30, 2009

Unable to find service IVsDiscoveryService

I had a problem with Visual Studio 2008. When I try to update service reference I have got following error message: "Unable to find service IVsDiscoveryService"...

To solve this do the following:
Open command prompt, go to the devenv folder (usually C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE) ande type following command:

devenv /resetskippkgs


You can save some time for finding visual studio disk and reinstalling visual studio.

Friday, November 20, 2009

Visual Studio macro for opening file from unit test folder

My test creates log file in current test execution folder dir. And sometime I need to open that file to see content. So, I made macro in visual studio for that:


Public Sub OpenLog()
Dim solutionPath As String
Dim solutionDir As String
Dim dirInSolution As String()

solutionPath = DTE.Solution.FullName
solutionDir = Path.GetDirectoryName(solutionPath)
solutionPath = solutionDir + "\TestResults"
dirInSolution = Directory.GetDirectories(solutionPath)

Dim lastTestDir As String
Dim currentDT As Date

For Each currentDir As String In dirInSolution
Dim ct As Date
ct = Directory.GetCreationTime(currentDir)
If (ct > currentDT) Then
currentDT = ct
lastTestDir = currentDir
End If
Next

' we have dir name
' open log file from that dir
Dim finalPath = lastTestDir + "\Out\trace.log"
DTE.ItemOperations.OpenFile(finalPath, ViewKind:=EnvDTE.Constants.vsViewKindTextView).Activate()
End Sub

Sunday, November 15, 2009

Using linq to select nodes in tree structure

If we have tree structure of object like this:

class C1
{
public List Children {get; set;}
public string Name {get; set;}
}


and have list of C1 object for example "listOfC1" we can use Linq to select object that match specific name path, for example "N1/N2/N3":


var result =
from c1 in listOfC1
where c1.Name == "N1"
from c2 in c1.Children
where c2.Name == "N2"
from c3 in c2.Children
where c3.Name == "N3"
select c3;

Friday, November 13, 2009

Errors in MSDN samples for LINQ

Microsoft has put on his site samples for LINQ. But on that page there are several errors. For example http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectManyCompoundfrom1 explain how to use "compound from". In theirs example it's written:

var pairs =
from a in numbersA,
b in numbersB
where a < b
select new {a, b};

but if you try this code you will get compile error:
"A query body must end with a select clause or a group clause"

The code should be:

var pairs =
from a in numbersA
from b in numbersB
where a < b
select new {a, b};

I am wondering how they gets their results.

Thursday, November 12, 2009

Total commander and SkyDrive

I was searching for solution how to map SkyDrive as a network drive or how to use skydrive as drive in Windows explorer. I found SkyDrive Explorer but I was very disappointed when I saw that I cannot use that drive in Total Commander.

But there is also plugin for Total Commander that enables using SkyDrive within TotalCommander. You can download plugin here.

Thursday, September 03, 2009

Wednesday, August 19, 2009

Google maps and GPS coordinates

To get gps coordinate from google maps type in address bar of your browser following command:

javascript:void(prompt('',gApplication.getMap().getCenter()));

Saturday, August 15, 2009

Enterprise library - real time log viewer

I made application for looking logs from enterprise library - logging application block in real time.
Application is still in alpha phase but I believe that it can be useful to someone even unfinished as it is. So, expect upgrade of this application, soon.

Link is http://www.mijalko.com/realtimelogviewer

Friday, August 07, 2009

Geneva framework and WCF service to WCF service identity delegation

In order to use credentials from WCF service to call method on other WCF service that also use authentication from Geneva Framework STS you can use code like following:

var principal = Thread.CurrentPrincipal as IClaimsPrincipal;
var callerTokens = principal.GetBootstrapTokens();

using (var serviceFactory = new ChannelFactory("WSFederationHttpBinding_IMyApi"))
{
serviceFactory.ConfigureChannelFactory();

if (callerTokens.Count > 0)
{
var service = serviceFactory.CreateChannelActingAs(callerTokens[0]);
service.SomeMethod();
}
}

Friday, July 24, 2009

Remote debugging and c#

You are trying to set remote debugging on remote computer that is in domain. You search internet and set everything it's write there.
  • Add the same user with the same password to the remote computer and add it to administrators group.
  • You setup firewall correctly (or even turn of firewall)
  • You set local security policy as it is described to MSDN
But when you try to connect you get something like: "Debugger on target computer cannot connect back to this..." and "Authentication failed."

In this case you should try to:
  • Turn of UAC
  • Run msvsmon.exe as user on local machine using command prompt and runas command (runas /user:localuser msvsmon.exe)
(localuser must have admin privileges on remote computer)

Enjoy in remote debugging.

Tuesday, July 14, 2009

Custom user for application pool

When I change default application pool for my WCF application and I set non admin credential I start to getting following error:

"secure channel cannot be opened because security negotiation with the remote endpoint has failed"

The thing was to set "Load User Profile" in settings for application pool to true

Friday, July 03, 2009

Zamena GPS Navigatora 4

Nastavak price Zamena GPS Navigatora 3

Juce mi je stigao novi GPS Navigator. Na svu srecu ovaj radi (za sada) lepo. Nazalost ova prica jos nije gotova zato sto mi uz novi uredjaj nisu poslali i novu garanciju. Poslao sam servisu mail u vezi garancije. Jos cekam odgovor...

Kad sve bude gotovo napisacu izvestaj o ovom procesu.

Task in progress.....

Monday, June 29, 2009

Zamena GPS Navigatora 3

Nastavak price iz Zamena GPS Navigatora 2

Danas sam bio pozitivno iznenadjen. Evo mail-a iz servisa:


Javljam se po prijemu Vaseg uredjaja na servis, uredjaj je pregledan I ustanovljena ne ispravnost. Porucio sam iz magacina novi, cim stigne bice Vam poslat.
Hvala na strpljenu

Friday, June 26, 2009

Bat file and current path

You can use this in your bat files to get current path

set currentpath=%~dp0

Zamena GPS Navigatora 2

Nastavak price Zamena GPS Naviagatora

Danas u 15:30 moj GPS navigator je isporucen servisu. Nesta pre toga sam dobio obavestenje iz servisa u kome pise:


Navigacia koju ste slali jos nije dostavljena servisu, cim dodje do nas bice pregledana I bice Vam javljeno.

Thursday, June 25, 2009

Zamena GPS Navigatora

Kupio sam GPS navigator Prestigio GeoVision 150 u Gigatron prodavnici (www.gigatronshop.com). Ispostvavilo se da je neispravn. Ovde cu da vam opisem kako je tekao tok reklamacije pa ce gore navedena firma dobiti od mene ili pohvale ili kritike.

- Dakle, danas u 13:00 doso je covek iz city expressa i uzeo neipsravan uredjaj. Kaze da ce biti u servisu gigatrona sutra do 13:00

...

Tuesday, June 09, 2009

Remove quotes from parameter in bat file


SET prop=%1
SET prop=###%prop%###
SET prop=%prop:"###=%
SET prop=%prop:###"=%
SET prop=%prop:###=%

Sunday, April 26, 2009

Second monitor preview

If you want to see what is on your second monitor (for example on your TV that is connected on your comp) you can use this application:

http://sites.google.com/site/mijalko/Home/second-monitor-preview

MSTest and TeamCity trouble

When I run test from Visual Studio all tests pass but when I setup test environment from Teamcity half of my test fails.

Problem was because some of assemblies was missing in mstest environment. Actually, I have used Enterprise library and I had custom trace listener. Test project had that trace listener in references. But when Teamcity runs mstest my assembly was missing in build agent working folder.

All assemblies that are not used directly in test (for example class from my assembly was dynamically loaded by enterprise library application logging block) will not be copied to test folder. Therefor, those test methods should be decorated with attribute like:


[DeploymentItem("MyTraceListener.dll")]


Somehow, this was not necessary when you run tests from Visuals Studio IDE.

I hope that I save you some time.

Wednesday, March 11, 2009

Hibernate (NHibernate) and Polymorphism

If you use lazy loading on base class, NHibernate will create proxy class of base class so you will not be able to use is operator to check type of object. For example:


abstract class Base
{
};

class A : Base
{
}

class B: Base
{
}

class C
{
public virtual Base BaseClass {get; set;}
}


If you now list all C objects from database and try to check of what type is C.BaseClass with

if (c.BaseClass is A)
{
}
else if (c.BaseClass is B)
{
}
else
{
//ERROR
}


you will get an error.

Simplest way to solve this problem is to add method in base class that will returns instance to itself:


abstract class Base
{
public virtual Base This()
{
return this;
}
};


Now, you can check:

if (c.BaseClass.This() is A)
{
}
else if (c.BaseClass.This() is B)
{
}

Tuesday, March 10, 2009

Firefox hangs

It happened to me that firefox won't shutdown. Also, when I choose to start new instance of firefox it fails.

I found that problem was in skype's addon for firefox . I uninstalled it (in firefox: Tools => Addon=> Extension) and everything works OK now.

Friday, February 20, 2009

Missing svc handler

Windows 2008 comes with installed .NET framework 3.5 but without installed IIS. When you install IIS you don't have support for WCF (there is no handler for svc). To install support for svc open command prompt and go to .net framework 3.0 location (:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\) and run:

servicemodelreg -i

Wednesday, February 04, 2009

An error occurred when verifying security for the message

One of the possible reasons:

- Check if the time on the server and the time on the client does not match.

Thursday, January 08, 2009

Resharper, Stylecop and type members layout

In order to resort type members layout to match requirements of StyleCop using ReSharper open ReSharper's settings, choose "Type Members Layout" and paste following XML:


<Patterns xmlns="urn:shemas-jetbrains-com:member-reordering-patterns">


 


  <!--Do not reorder COM interfaces-->


  <Pattern>


    <Match>


      <And Weight="100">


        <Kind Is="interface"/>


        <HasAttribute CLRName="System.Runtime.InteropServices.InterfaceTypeAttribute"/>


      </And>


    </Match>


  </Pattern>


 


  <!--Special formatting of NUnit test fixture-->


  <Pattern RemoveAllRegions="true">


    <Match>


      <And Weight="100">


        <Kind Is="class"/>


        <HasAttribute CLRName="NUnit.Framework.TestFixtureAttribute" Inherit="true"/>


      </And>


    </Match>


 


    <!--Setup/Teardow-->


    <Entry>


      <Match>


        <And>


          <Kind Is="method"/>


          <Or>


            <HasAttribute CLRName="NUnit.Framework.SetUpAttribute" Inherit="true"/>


            <HasAttribute CLRName="NUnit.Framework.TearDownAttribute" Inherit="true"/>


            <HasAttribute CLRName="NUnit.Framework.FixtureSetUpAttribute" Inherit="true"/>


            <HasAttribute CLRName="NUnit.Framework.FixtureTearDownAttribute" Inherit="true"/>


          </Or>


        </And>


      </Match>


    </Entry>


 


    <!--All other members-->


    <Entry/>


 


    <!--Test methods-->


    <Entry>


      <Match>


        <And Weight="100">


          <Kind Is="method"/>


          <HasAttribute CLRName="NUnit.Framework.TestAttribute" Inherit="false"/>


        </And>


      </Match>


      <Sort>


        <Name/>


      </Sort>


    </Entry>


  </Pattern>


 


  <!--Default pattern-->


  <Pattern RemoveAllRegions="true">


 


    <!--Delegates-->


    <Entry>


      <Match>


        <And Weight="100">


          <Access Is="public"/>


          <Kind Is="delegate"/>


        </And>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Name/>


      </Sort>


    </Entry>


 


    <!--Fields and constants-->


    <Entry>


      <Match>


        <Or>


          <Kind Is="field"/>


          <Kind Is="constant"/>


        </Or>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Kind Order="constant"/>


        <Readonly/>


        <Static/>


        <Name/>


      </Sort>


    </Entry>


 


    <!--Enums-->


    <Entry>


      <Match>


        <Kind Is="enum"/>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Name/>


      </Sort>


    </Entry>


 


    <!--Constructors. Place static one first-->


    <Entry>


      <Match>


        <Kind Is="constructor"/>


      </Match>


      <Sort>


        <Static/>


        <Access Order="public internal protected-internal protected private" />


      </Sort>


    </Entry>


 


    <!--Destructors. Place static one first-->


    <Entry>


      <Match>


        <Kind Is="destructor"/>


      </Match>


      <Sort>


        <Static/>


        <Access Order="public internal protected-internal protected private" />


      </Sort>


    </Entry>


 


    <!-- Events -->


    <Entry>


      <Match>


        <Kind Is="event"/>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Name/>


      </Sort>


    </Entry>


 


    <!--Properties-->


    <Entry>


      <Match>


        <And>


          <Kind Is="property"/>


          <Not>


            <Kind Is="indexer"/>


          </Not>


        </And>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Static/>


        <Abstract/>


        <Virtual/>


        <Override/>


        <Name/>


      </Sort>


    </Entry>


 


    <!--Indexers-->


    <Entry>


      <Match>


        <Kind Is="indexer"/>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Static/>


        <Abstract/>


        <Virtual/>


        <Override/>


        <Name/>


      </Sort>


    </Entry>


 


    <!--Methods-->


    <Entry>


      <Match>


        <And>


          <Or>


            <Kind Is="method"/>


            <Kind Is="operator"/>


            <HandlesEvent />


          </Or>


          <Not>


            <Kind Is="destructor"/>


          </Not>


        </And>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Static/>


        <Abstract/>


        <Virtual/>


        <Override/>


        <Name/>


      </Sort>


    </Entry>


 


    <!--all other members-->


    <Entry/>


 


    <!--nested types-->


    <Entry>


      <Match>


        <Kind Is="type"/>


      </Match>


      <Sort>


        <Access Order="public internal protected-internal protected private" />


        <Static/>


        <Abstract/>


        <Virtual/>


        <Override/>


        <Name/>


      </Sort>


    </Entry>


  </Pattern>




Now, choose Cleanup Code.

( tnx to Jordan Dimitrov)