Tag Archives: software

Reverting a commit using git bash and bc3

After doing it the wrong way (see ‘wrong ways to revert a commit’), here is a good way to revert a commit that accidentally inserted in the past.

Reverting a commit

  1. Checkout the wanted branch, with the bad commit (lets mark it as SHA-1).
  2. git revert –no-commit SHA-1
  3. Solve merge problem
  4. Commit at the end

Solving merge conflicts on the way

Assuming your mergetool is configured.

Note: see ‘config BC3 as a mergetool‘ if you need to config your mergetool to BC3.

Solve your merge using the following command:

git mergetool

Config BC3 as a mergetool

Follow the instructions here:

http://www.scootersoftware.com/support.php?zz=kb_vcs#gitwindows

Note: If you use the Git for Windows’ Bash Command Prompt instead of the default Windows Command Prompt, you need to escape the $ character with .

Wrong ways to revert a commit

I think that its important to know the wrong ways of doing things also, here are some I tried and my personal conclusions:

Comparing folders and files

After trying that option here are some of this strategy disadvantages:

  1. Need to compare a lot of files ==> lot of effort.
  2. Do a 2 way comparison and can’t know what was the base change to decide. so, you guess by memory.
    1. This solution is limited by your memory power, the bigger the change you made the bigger the effort.
  3. Its not safe, you can make human errors and effect others commits.

Cherry-pick

Another solution proposed, sounds good but have its limits:

If the commit to undo is far in the past, you’ll need to:

  1. go to one commit before the bad commit
  2. start cherry-pick commits one after the bad one.
  3. merge 

While this is  a solution, what you doing is – undoing one commit – the hard way, and this post describes exactly how to do this strategy in one strike.

Resources

Git – git-revert Documentation.

git-revert(1) Manual Page

Vim Commands Cheat Sheet

 

Productivity Tip: Clipboard Manager

In the beginning, there was darkens, and the clipboard was a scalar copier.

And the developers said: let there be a vector copied and there was ‘Clipboard Manager’ :-).

Use case description

clipx

copy, paste to a notepad (for later use), paste to the target application.

again, copy, paste to a notepad (for later use), paste to the target application.

And again, … and again…

ClipX

ClipX is a tiny clipboard history manager. It is sweet, it is free, use it.

Resources

Sparx, Enterprise Architect, Class diagram quick start

Abstract

In this post we’ll see how to use EA to draw a basic class diagram quickly and with easy. In the end of this post you should be able to start working with EA as a reverse engineering tool and as a UML drawer. The added values of this are:

  • The ability to draw UML faster then a board + marker / paper and a pen.
  • Reusability of UML / designs (in contrast to Visio / paper / board drawing, reason: elements change over multi-drawing >> update maintenance that EA solves).

Quick start guide

Getting started

Downloading EA (Enterprise Architect)

Importing Source Code

Importing your code

Inserting an existing entity

I found that there are two ways  to do the job:

  1. Right click the canvas, select “Insert Existing Element”.
  2. A tip I found here: http://www.sparxsystems.in/blog/enterprise-architect-tips-compilation1/

Tip #2: Insert Existing Element Draw connector to a model Element One can insert an existing model element and establish a relationship while drawing a new connector Follow usual steps to draw a connector, but press “Shift” before choosing the type of relationship to be created, this will invoke the “Select Existing Element” dialog to choose a model element instead of creating a new element. Connector-InsertExistingElement

Insert Related ElementsRelating an entity to an existing entity

Right-click on element >> Insert Related Elements Read more here…

Prettifying the view

Feature Visibility

You can set a collection of options to display or hide the features of that element on a specific diagram.

  1. Select the class element
  2. Right mouse click >> “Feature and compartment visibility (Ctrl+Shift+Y)”
  3. Disable attributes and operations accordingly.

Auto-size elements

After you shrink the size of the elements using Feature Visibility, you can auto-size the element to take minimal space. To Auto-Size select the wanted elements and press Alt+Z

Define how features are displayed on the diagramDefine how features are displayed on the diagram

In most cases you only need the class/entity name, some operation (without the parameters) and their return value and the relations between the entities, everything else detracts. To normalize the view:

  • Select Menu >> Diagram >> Properties (F5)
  • Select the wanted view behavior and press OK

Designing

Adding new entities

Adding unrelated entityAdding new entity/class

Right click an empty space on the canvas and select ‘New element or connector’, select the wanted entity (usually a class). Name it and press OK. Read more here…

Adding related entity

If you select an element you’ll notice that on the right there is a ‘quick tools’ quick tools icons. Select the up arrow and drag it to an empty space on the canvas. Once released a menu will open, select the relation type while holding the shift, this will open a search for known entity.

Resources

Quick Start Guide

Useful tips found

More comprehending guides found

How to: create your own ‘Custom Tool’ (AKA: XMLcode generator)

What is a Custom Tool?

Here are some statements which describe a custom tool:

It’s a file generator

It makes code-behind files

It extends Visual Studio

It’s stored in a ComVisible DLL file

It uses the Registry

Quoted from ‘Custom Tools Explained‘ 

Steps to create custom tool

  1. Create Dll project for custom tool (AKA: Repository.CodeGenerator).
    1. Add a new ‘RepositoryCodeGenerator.reg’ file with the below content.
    2. Add your ‘Repository.xsd’ XSD file.
    3. Add your new ‘Generator.cs’ class file (see the content of ‘Generator.cs’).
    4. Make sure your project is COM visible.

[csharp title=”<h4>Content of Generator.cs</h4>”]
using Microsoft.VisualStudio.TextTemplating.VSHost;
using System.Runtime.InteropServices;

namespace Repository.CodeGenerator
{
[Guid("11111111-1111-1111-1111-111111111111")]
public class Generator : BaseCodeGenerator
{
protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
{
return new MyRepositoryBuilder(MyGeneratorErrorCallback).MyGenerateRepositoryCode(inputFileContent);
}

public override string GetDefaultExtension()
{
return ".Designer.cs";
}
}
}
[/csharp]
[text title=”<h4>Post buiild event of Repository.CodeGenerator</h4>”]

xcopy /y "$(ProjectDir)Repository.xsd" "$(DevEnvDir)….xmlschemas"
xcopy /y "$(ProjectDir)Repository.xsd" "$(SolutionDir)MyRuntime$(OutDir)"
call "$(DevEnvDir)….VCvcvarsall.bat"
regasm /codebase "$(TargetPath)"
regedit /s "$(ProjectDir)RepositoryCodeGenerator.reg"

[/text]
[text title=”<h4>Content of RepositoryCodeGenerator.reg</h4>”]

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINESOFTWAREMicrosoftVisualStudio10.0Generators{00000000-0000-0000-0000-000000000000}RepositoryCodeGenerator2.0]
"GeneratesDesignTimeSource"=dword:00000001
"CLSID"="{11111111-1111-1111-1111-111111111111}"
<em id="__mceDel">
[/text]
[csharp title=”<h4>Content of MyGenerateRepositoryCode</h4>”]
public byte[] GenerateRepositoryCode(string inputFileContent, bool withAutoGenCode)
{
try
{
ValidateRepository(@"Repository.xsd", inputFileContent);

StringReader stringReader = new StringReader(inputFileContent);
StringWriter codeWriter = new StringWriter();
XDocument xDocument = XDocument.Load(stringReader, LoadOptions.SetLineInfo);

if (xDocument.Root != null)
{
CodeDomProvider codeDomProvider = new CSharpCodeProvider();

CodeNamespace buildNamespace = BuildNamespace(xDocument.Root);

CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions
{
BracingStyle = "C",
BlankLinesBetweenMembers = false
};
if (withAutoGenCode)
{
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
codeCompileUnit.Namespaces.Add(buildNamespace);
codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, codeWriter, codeGeneratorOptions);
}
else
{
codeDomProvider.GenerateCodeFromNamespace(buildNamespace, codeWriter, codeGeneratorOptions);
}

}
return Encoding.UTF8.GetBytes(codeWriter.ToString());
}
catch (Exception e)
{
// handle exception …
}
return null;
}
[/csharp]

 

[csharp title=”<h4>Example 'BuildNamespace function'</h4>”]
internal CodeNamespace BuildNamespace(XElement root)
{
XAttribute rootAttrib = root.Attribute("Name");
CodeNamespace ns = null;
if (rootAttrib != null && rootAttrib.Value != "")
{
XAttribute versionAttr = root.Attribute("Version");
if (versionAttr != null)
{
double ver;
if (double.TryParse(versionAttr.Value, out ver))
{
version = ver;
}
}

ns = new CodeNamespace(rootAttrib.Value);
foreach (Type type in basicTypes)
{
ns.Imports.Add(new CodeNamespaceImport(type.Namespace));
}
BuildClass(ns, null, root);
}
return ns;
}
[/csharp]

… and so on…

Remarks

  • Replace ‘00000000-0000-0000-0000-000000000000’ with a newly generated GUID.
  • replace ‘11111111-1111-1111-1111-111111111111′ with newly generated GUID.

Resources

Custom Tools Explained – CodeProject.

XSD -> Classes Generator Custom Tool (radically new and extensible) – Daniel Cazzulino’s Blog.

BaseCodeGenerator Class (Microsoft.VisualStudio.TextTemplating.VSHost).

Snippet: Clean project using msbuild C# code

After a small research, I’ve found that the best way to clean a project is to use MsBuild /clean command.
I couldn’t do that using the System.MsBuild namespace, so I’ve used the Process to do the job.

Here are the steps to do it:

Get .Net 4 full installation folder

[csharp]
var net4InstallPath = Registry.GetValue(
@"HKEY_LOCAL_MACHINESOFTWAREMicrosoftNET Framework SetupNDPv4Full",
"InstallPath", null);
[/csharp]

Combine msbuild executable

[csharp]
string msBuildExeFilePath =
Path.Combine((string)net4InstallPath, "msbuild.exe");
[/csharp]

Configure msbuild process to clean the project

[csharp]
string arguments = string.Format("{0} /t:Build;Clean", Path.GetFileName(_loadedProject.FullPath));

var msBuildProcess = new Process
{
StartInfo =
{
FileName = msBuildExeFilePath,
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = arguments,
WorkingDirectory = _loadedProject.DirectoryPath,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}
};
[/csharp]

Execute msbuild and check the results

[csharp]
msBuildProcess.Start();
msBuildProcess.WaitForExit();

string msBuildErrors = msBuildProcess.StandardError.ReadToEnd();
string msBuildOutput = msBuildProcess.StandardOutput.ReadToEnd();
[/csharp]

Complete code snippet

[csharp]
public void CleanProject(string tempPath)
{
var net4InstallPath = Registry.GetValue(@"HKEY_LOCAL_MACHINESOFTWAREMicrosoftNET Framework SetupNDPv4Full", "InstallPath", null) as string;
if (net4InstallPath == null)
{
var message = Resources.Net_4_installation_directory_not_found;

logger.WriteToLog(TargetLoggers.All, LogLevel.ErrorLevel, message);
throw new FileNotFoundException(message);
}

var msBuildExeFilePath = Path.Combine(net4InstallPath, "msbuild.exe");
if (!File.Exists(msBuildExeFilePath))
{
var message = string.Format(Resources.MSBuild_file_not_found_in_Net_4_install_dir, net4InstallPath);

logger.WriteToLog(TargetLoggers.All, LogLevel.ErrorLevel, message);
throw new FileNotFoundException(message);
}

var arguments = string.Format("{0} /t:Build;Clean", Path.GetFileName(_loadedProject.FullPath));

var msBuildProcess =
new Process
{
StartInfo =
{
FileName = msBuildExeFilePath,
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = arguments,
WorkingDirectory = _loadedProject.DirectoryPath,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};

msBuildProcess.Start();
msBuildProcess.WaitForExit();

string msBuildErrors = msBuildProcess.StandardError.ReadToEnd();
string msBuildOutput = msBuildProcess.StandardOutput.ReadToEnd();

if (msBuildErrors != string.Empty)
{
var message = new StringBuilder();

message
.AppendLine("MSBuild errors detected: ")
.AppendLine(msBuildErrors)
.AppendLine("MSBuild output dump:")
.AppendLine(msBuildOutput);

logger.WriteToLog(TargetLoggers.All, LogLevel.ErrorLevel, message.ToString());

throw new ApplicationException(message.ToString());
}
}
[/csharp]

Resources

Recommended free book – Microsoft Application Architecture Guide, 2nd Edition

Just finished reviewing the below book – A must book for anyone interesting in enterprise architecture.

 

Appetizer screenshots

 

TOC

 

Resources

Microsoft Application Architecture Guide, 2nd Edition.

Project template – using MsBuild::GetRegistryValue for 32 and 64 registry keys

Under <Project …> you can, for example, dynamically load your DLL, which installed anywhere the user chooses in the installation phase, and under 32/64 bits – respectively to his machine:

[xml]
<UsingTask
AssemblyFile="$([MSBuild]::Unescape(
   $([MSBuild]::GetRegistryValueFromView(‘HKEY_LOCAL_MACHINESOFTWAREMyProject2.0’,
   ‘WinFuseInstallDir’, null, RegistryView.Registry64, RegistryView.Registry32))Tasks.dll))"
   TaskName="CompileRepository" />
[/xml]

The above command will check first under the 64bit registry key/value: [HKEY_LOCAL_MACHINESOFTWAREWow6432NodeMyProduct4.2MyInstallDir]
and if key not found will search under the 32bit key/value:  [HKEY_LOCAL_MACHINESOFTWAREMyProduct4.2MyInstallDir]

Remark

MSBuild::GetRegistryValueFromView have a bug (e.g. ‘c:program files (x86)’ from the registry will be returned as: ‘c:program files %28×86%29’), using
MSBuild::Unescape solves this issue.

Resources

Property Functions.

‪How to fix CamStudio WaveoutGetSelectControl failed message

A lot of time we do knowledge transfer, teaching each other  pieces of expertise and such.

In such cases it’s a good idea just to record the process for ‘offline’ view, or to syndicate the knowledge in your team’s blog …

After searching for a free, good for the job tool I’ve found CamStudio.

CamStudio is able to record all screen and audio activity on your computer and create industry-standard AVI video files

After installing CamStudio I’ve encountered a problem and fixed it using the following YouTube video (jump to the middle of the movie for the solution).

If you found this tool helpful, don’t forget to contribute a penny.

Free Reflector / DotNet decompiler tools

Free Reflector

Below you can find free Reflector tools I’ve found / collected and others suggested.  They are alternatives to ‘Red Gate’s DotNet Reflector’.

I used to love Reflector, It was such a wonderful tool. I used to learn code and tricks from the original .Net code by reverse-engineering it. Since Feb 2011, RedGate took over Reflector and it’s not a free reflector anymore. I’ve come to a point where I need a new decompiler tool, I am ready for something new.

What is DotNet reflector / Decompiler tool?

From Wikipedia, the free encyclopedia

A decompiler is the name given to a computer program that performs, as far as possible, the reverse operation to that of a compiler. That is, it translates a file containing information at a relatively low level of abstraction (usually designed to be computer readable rather than human readable) into a form having a higher level of abstraction (usually designed to be human readable). The decompiler does not reconstruct the original source code, and its output is far less intelligible to a human than original source code.

Free Reflector tools

  • dotPeek – ‘dotPeek is a free-of-charge .NET decompiler from JetBrains, the makers of ReSharper and more developer productivity tools.’
  •  JustDecompile – ‘JustDecompile makes it easy to recover lost source code or peer into assemblies to discover the root cause of an external bug. Integrates with the powerful Visual Studio add-in, JustCode, for inline decompilation. Free for everyone, forever.’
  • CodeReflect – ‘DevExtras .NET CodeReflect is a simple yet advanced free .NET assembly browser/decompiler. It is a free alternative to Red Gate’s/Lutz Roeder’s .NET Reflector.’
  • ILSpy – ‘ILSpy is the open-source .NET assembly browser and decompiler. Development started after Red Gate announced that the free version of DotNet Reflector would cease to exist by end of February 2011.’

Sources