Thursday, September 28, 2017

Revursive SQL

Given a lookup table Mappings such as follows

ID OldValue NewValue
1 A B
2 C D
3 B E
4 E F
5 G H


CREATE TABLE Mappings (id int , OldValue nvarchar, NewValue nvarchar)

INSERT INTO Mappings (id, OldValue, NewValue) VALUES   (1,'A','B')
INSERT INTO Mappings (id, OldValue, NewValue) VALUES   (2,'C','D')
INSERT INTO Mappings (id, OldValue, NewValue) VALUES   (3,'B','E')
INSERT INTO Mappings (id, OldValue, NewValue) VALUES   (4,'E','F')
INSERT INTO Mappings (id, OldValue, NewValue) VALUES   (5,'G','H')

Given entry A, how do we follow the table all the way to get to the final value of F?

We can obviously do this using a Recursive Function:


CREATE FUNCTION Map(@OldValue nvarchar)
RETURNS nvarchar
AS
BEGIN
DECLARE @RET nvarchar;
SELECT @RET = NewValue FROM Mappings WHERE OldValue = @OldValue
IF (@RET IS NULL) SET @RET = @OldValue
ELSE SET @RET = dbo.Map(@RET)
RETURN @RET
END
GO

SELECT dbo.Map('C') -- returns D
SELECT dbo.Map('D') -- returns D
SELECT dbo.Map('A') -- returns F
SELECT dbo.Map('B') -- returns F


But can we do it just using normal SQL Queries? The answer is yes!

This shows the working


DECLARE @startingPoint NVarchar(max) = 'A';

 
  with working_tree as (
   select [OldValue] , [NewValue]
   from [Mappings]
   where [OldValue] =  @startingPoint-- this is the starting point you want in your recursion
   union all
   select  c.[OldValue], c.[NewValue]
   from [Mappings] c
     join working_tree p on p.[NewValue] = c.[OldValue]  -- this is the recursion
)

select *
from working_tree;

OldValue NewValue
A               B
B               E
E               F


And this is the final form.


  with working_tree as (
   select [OldValue] , [NewValue]
   from [Mappings]
   where [OldValue] =  @startingPoint-- this is the starting point you want in your recursion
   union all
   select  c.[OldValue], c.[NewValue]
   from [Mappings] c
     join working_tree p on p.[NewValue] = c.[OldValue]  -- this is the recursion
)
select t1.NewValue
from working_tree t1
LEFT JOIN [Mappings] t2 ON t2.OldValue = t1.NewValue
where t2.OldValue IS NULL

This returns F, as expected.

Wednesday, September 27, 2017

SQL Pick up Batch in one go, and mark them as picked atomically while returning them

CREATE PROCEDURE [dbo].[sp_ProcessBatch]
@BatchSize int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

declare @ProcessorState bit
set @ProcessorState = 1


UPDATE NotificationMeta
SET NotificationMeta.StateID = 2, -- UPDATE STATE AS PART OF SELECT AND OUTPUT
NotificationMeta.TimePicked = GETUTCDATE(),
RetryCount = RetryCount + 1
OUTPUT NotificationMeta2.ID, NotificationMeta2.EchoToken  -- RETURN PICKED ROWS
FROM NotificationMeta
JOIN
(SELECT TOP (@BatchSize) nd.* FROM NotificationMeta
 WITH (UPDLOCK,READPAST) -- TO ENSURE NO MULTIPLE UPDATES TO SAME ROW
 JOIN NotificationData nd ON ID = NotificationMeta.NotificationID
 WHERE StateID = 1 AND GETUTCDATE() < ExpiryTime
 ORDER BY nd.EntryTime ASC, Priority ASC) AS NotificationMeta2
ON NotificationMeta.NotificationID = NotificationMeta2.ID

END

Sunday, September 24, 2017

Debug Windows Services

Out of the box, one cannot debug a Windows Service easily through Visual Studio.

Making this possible via code is very easy though.

One just needs to change the code in Program.cs to

#if DEBUG
           Service1 debugInstance = new Service1();
           debugInstance.OnDebug();

           Thread.Sleep(Timeout.Infinite);
#else
           ServiceBase[] ServicesToRun;
           ServicesToRun = new ServiceBase[]
           {
               new Service1()
           };
           ServiceBase.Run(ServicesToRun);
#endif


And add an OnDebug method to the partial class that implements ServiceBase, and has the OnStart() and OnStop() methods.

  public void OnDebug()
        {
        }


This will now be your entry point into debugging your Windows Service through Visual Studio.

Wednesday, June 8, 2016

Moving from SVN to GITLAB


  1. Create C:\GITLAB
  2. CD to C:\GITLAB
  3. Create new empty repository in GITLAB (browser)
  4. Create New Project
  5. Give it UniqueName (get newGitLabProjectURL)
  6. Set Visibility Level to Private
  7. Click Create Project
  8. Run command equivalent to git svn clone http://svnServer:port/svn/DeveloperRepo/Project
  9. CD to project folder 
  10. Run command equivalent to git svn rebase
  11. git config --global user.name "YourUsernameHere"
  12. 11. git config --global user.email "yourEmail@Domain.com"
  13. cd existing_folder
  14. git init
  15. git remote add origin http://newGitLabProjectUrl.git
  16. git add .
  17. git commit
  18. git push -u origin master

Wednesday, March 18, 2015

Location of database on hard disk and size by table

Location of database on hard disk



SELECT type_desc, physical_name, size
   FROM sys.database_files


Size by Table

SELECT
    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB,
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
    sys.tables t
INNER JOIN     
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
    sys.schemas s ON t.schema_id = s.schema_id
WHERE
    t.NAME NOT LIKE 'dt%'
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255
GROUP BY
    t.Name, s.Name, p.Rows
ORDER BY
    t.Name

Monday, September 1, 2014

Changing logging level for Visual Studio

By default Visual Studio is not very heavy on logging. However if a developer wants to increase logging levels, there is a very easy way.


  • Click on Tools
  • Click on Options
  • Click on Project and Solutions
  • Click on Build and Run
  • Change settings like shown below.


This way when you build a solution, you will be able to see exactly what is happening.





Friday, May 16, 2014

Restore Database from SQL scripts.

I recently had to move a database from one server to another, using SQL Server Management Studio.
I first made use of Generate Scripts to create these SQL files.


  • Right click the database you want to generate scripts for (not the table) and select tasks - generate scripts
  • Next, select the requested table/tables, views, stored procedures, etc (from select specific database objects)
  • Click advanced - select the types of data to script
  • Click Next and finish
http://msdn.microsoft.com/en-us/library/hh245282.aspx


I chose to create the schema on its own, and then the data on its own, one file per table.
Even though the largest SQL files was no larger than 100Mb, SQL Server management Studio was still complaining and running out of memory.

So instead I opted to use the SQLCMD tool, which is leaner, faster, and does not complain of memory issues

This is how I used it.

sqlcmd -S ServerName -i Script.sql -o DbLogFile.log

http://technet.microsoft.com/en-us/library/ms162773.aspx

Tuesday, April 22, 2014

Entity Framework Migrations

Below are some commands which are useful when it comes to migrating your database schema when using Entity Framework.

These commands needs to be run through Tools > NuGet Package Manager > Package Manager Console , under Visual Studio.

The code for this can be found under this folder ...\packages\EntityFramework.6.1.0\tools\EntityFramework.psm1

Enable-Migrations: Enables Code First Migrations in a project.
Add-Migration: Scaffolds a migration script for any pending model changes.
Update-Database: Applies any pending migrations to the database.
Get-Migrations: Displays the migrations that have been applied to the target database.

Enable-Migrations
Enables Code First Migrations in a project.

Syntax
Enable-Migrations [-EnableAutomaticMigrations] [[-ProjectName] <String>]
  [-Force] [<CommonParameters>]
Description
Enables Migrations by scaffolding a migrations configuration class in the project. If the  target database was created by an initializer, an initial migration will be created (unless automatic migrations are enabled via the EnableAutomaticMigrations parameter).

Parameters
-EnableAutomaticMigrations
Specifies whether automatic migrations will be enabled in the scaffolded migrations configuration. If ommitted, automatic migrations will be disabled.

-ProjectName <String>
Specifies the project that the scaffolded migrations configuration class will be added to. If omitted, the default project selected in package manager console is used.

-Force
Specifies that the migrations configuration be overwritten when running more than once for given project.

<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.


Add-Migration
Scaffolds a migration script for any pending model changes.

Syntax
Add-Migration [-Name] <String> [-Force]
  [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] [-ConnectionStringName <String>]
  [-IgnoreChanges] [<CommonParameters>]

Add-Migration [-Name] <String> [-Force]
  [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] -ConnectionString <String>
  -ConnectionProviderName <String> [-IgnoreChanges] [<Common Parameters>]
Description
Scaffolds a new migration script and adds it to the project.

Parameters
-Name <String>
Specifies the name of the custom script.

-Force
Specifies that the migration user code be overwritten when re-scaffolding an existing migration.

-ProjectName <String>
Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.

-StartUpProjectName <String>
Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

-ConfigurationTypeName <String>
Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.

-ConnectionStringName <String>
Specifies the name of a connection string to use from the application’s configuration file.

-ConnectionString <String>
Specifies the the connection string to use. If omitted, the context’s default connection will be used.

-ConnectionProviderName <String>
Specifies the provider invariant name of the connection string.

-IgnoreChanges
Scaffolds an empty migration ignoring any pending changes detected in the current model. This can be used to create an initial, empty migration to enable Migrations for an existing database. N.B. Doing this assumes that the target database schema is compatible with the current model.

<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.


Update-Database
Applies any pending migrations to the database.

Syntax
Update-Database [-SourceMigration <String>]
  [-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>]
  [-StartUpProjectName <String>] [-ConfigurationTypeName <String>]
  [-ConnectionStringName <String>] [<CommonParameters>]

Update-Database [-SourceMigration <String>] [-TargetMigration <String>]
  [-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] -ConnectionString <String>
  -ConnectionProviderName <String> [<CommonParameters>]
Description
Updates the database to the current model by applying pending migrations.

Parameters
-SourceMigration <String>
Only valid with -Script. Specifies the name of a particular migration to use as the update’s starting point. If ommitted, the last applied migration in the database will be used.

-TargetMigration <String>
Specifies the name of a particular migration to update the database to. If ommitted, the current model will be used.

-Script
Generate a SQL script rather than executing the pending changes directly.

-Force
Specifies that data loss is acceptable during automatic migration of the
database.

-ProjectName <String>
Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.

-StartUpProjectName <String>
Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

-ConfigurationTypeName <String>
Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.

-ConnectionStringName <String>
Specifies the name of a connection string to use from the application’s configuration file.

-ConnectionString <String>
Specifies the the connection string to use. If omitted, the context’s default connection will be used.

-ConnectionProviderName <String>
Specifies the provider invariant name of the connection string.

<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.


Get-Migrations
Displays the migrations that have been applied to the target database.

Syntax
Get-Migrations [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] [-ConnectionStringName <String>]
  [<CommonParameters>]

Get-Migrations [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] -ConnectionString <String>
  -ConnectionProviderName <String> [<CommonParameters>]
Description
Displays the migrations that have been applied to the target database.

Parameters
-ProjectName <String>
Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.

-StartUpProjectName <String>
Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

-ConfigurationTypeName <String>
Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.

-ConnectionStringName <String>
Specifies the name of a connection string to use from the application’s configuration file.

-ConnectionString <String>
Specifies the the connection string to use. If omitted, the context’s default connection will be used.

-ConnectionProviderName <String>
Specifies the provider invariant name of the connection string.

<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.

Visualise XML beautifully

While looking for a way on how to show and traverse XML in a decent way, I came across this site: http://xmlgrid.net/ .

This is a really useful site, where you can upload your own XML, look at or edit the data, and also get the XPath of the current node.

Kudos to the devs!

Tuesday, October 22, 2013

Changing which Xcode version to use on a Mac

On a Mac you can have two different versions of Xcode happily living side by side.
In my case I needed to be able to use both Xcode 4.6, and Xcode 5.0.
My build machine had version 5.0, and I needed to use version 4.6 temporarily.
This is how I carried it out.

 Install the old Xcode under /Applications/XCode4/
·         Check which Xcode version the xcodebuild version uses
o   Run xcodebuild –version
o   This for now will be Version 5.0
·         Check which path Xcodebuild uses
o   Run xcode-select --print-path
o   This should be /Applications/Xcode.app/Contents/Developer
·         Change which xcode version to use
o   Sudo xcode-select –switch /Applications/XCode4/Xcode.app/Contents/Developer
o   Enter the account/admin password
·         Check which Xcode version the xcodebuild version now uses
o   Run xcodebuild –version
o   This for now will be Version 4.6.3
·         Check which path Xcodebuild uses
o   Run xcode-select –print-path
o   This should be /Applications/XCode4/Xcode.app/Contents/Developer
·         Call Xbuildcode as normal  

To revert this change, we will need to :
·         Check which Xcode version the xcodebuild version uses
o   Run xcodebuild –version
o   This for now will be Version 4.6.3
·         Check which path Xcodebuild uses
o   Run xcode-select –print-path
o   This should be /Applications/XCode4/Xcode.app/Contents/Developer
·         Change which xcode version to use
o   Sudo xcode-select –switch /Applications /Xcode.app/Contents/Developer
o   Enter the account/admin password
·         Check which Xcode version the xcodebuild version now uses
o   Run xcodebuild –version
o   This for now will be Version 5.0
·         Check which path Xcodebuild uses
o   Run xcode-select –print-path
o   This should be /Applications/Xcode.app/Contents/Developer

·         Call Xbuildcode as normal  

Wednesday, August 28, 2013

Send email using Powershell

Sending an email using Powershell couldn't be easier. You just need to use the Send-MailMessage commandlet.

It is used as follows.

Send-MailMessage
 -From "ReubenBartolo@test.com"
-To "ReubenBartolo@test.com"
-Subject "Hello"
-Body "World"
-SmtpServer "mail.test.com"


To add more than one recepient, just add as follows.

-To "Receiver1@test.com","Receiver2@test.com"

Thursday, August 22, 2013

Force Powershell to always create an array

Imagine you have a file called buildLog.txt, which contains

1
2
3
22

Now, also imagine you want to find out if a line contains a specific number in this text file.

You can run a command like this:


$allWarnings = Select-String build.log.txt -Pattern "2"  | Select-Object Line,LineNumber,FileName | Sort-Object -Property Line -Unique ; if ($allWarnings.Count -gt 0) { $allWarnings | Format-List; }

This works correctly and returns:

Line       : 2
LineNumber : 2
Filename   : build.log.txt

Line       : 22
LineNumber : 4
Filename   : build.log.txt


But if you run it to check if any sentences contain a 1, something weird happens:

$allWarnings = Select-String build.log.txt -Pattern "1"  | Select-Object Line,LineNumber,FileName | Sort-Object -Property Line -Unique ; if ($allWarnings.Count -gt 0) { $allWarnings | Format-List; }

This returns no results. This is very weird and unexpected behaviour, to say the least. But the reason can be understood once you break the steps down.

In the first case, we have multiple results, which creates an array. Then we do a .Count on this array, and we get the result.
In the second case, we only have one result. This is an object, and not an array. Therefore this has no .Count property, so .Count will return null.

The fix is luckily very easy. Simply force the result to always be an array. This is done by simply adding one keyword in front.

[array]$allWarnings = Select-String build.log.txt -Pattern "1"  | Select-Object Line,LineNumber,FileName | Sort-Object -Property Line -Unique ; if ($allWarnings.Count -gt 0) { $allWarnings | Format-List; }

This now works as expected.


Line       : 1
LineNumber : 1
Filename   : build.log.txt


Success!

Monday, August 12, 2013

Perforce Merging Advanced Options

When you are a Perforce power user, you carry out a lot of complex merges between different branches. Many times you will need to make use of the advanced options, and I find myself having to consult the documentation every time. So I am pasting the definitions down here:


Limit revision rangePerforce keeps track of which revisions of a source file have already been integrated to a target file. Normally integrate opens the target if any source revisions have not yet been integrated. You can restrict which source files revisions will be considered by entering a revision range here.

  • You can use symbolic revision numbers (for example, "@12345") or absolute revision numbers(for example, "#45").
  • If you enter a "starting with" revision, no source revisions prior to it will be considered. If you don't supply the "@" or "#" prefix, "@" will be assumed.
  • If you enter an "ending with" revision, no higher source revisions higher are considered. If you omit the "@" or "#" prefix, it is assumed to be the same type of revision number as the starting revision you supplied, or "@" if you didn't specify a starting revision.
Put open files in changelistIf your client workspace has more than one pending changelist, you can select one in which to open the files selected for integration..
Enable baseless mergesNormally Perforce only opens a target file for integrate if it can find a common base between it and the source file to use as a base for doing a merge. A target file and source file not directly related to each other by branching have no common base. By default, the target are not opened in this case. You can use the "enable baseless merges" option to force target files to be opened even if they are not related to source files by branching. If you do this, Perforce arbitrarily chooses the #1 revision of the source files to use as a merge base.

Permit deletes/re-adds
If the ending revision of the source file is a deleted file, Perforce normally opens the target file for delete unless the target file has any revisions that have not themselves been integrated to the source file. If the source file exists and the target file does not, Perforce normally opens the target file for branch/add unless the target file is a deleted file. Checking the "permit deletes/re-adds" option makes the integrate command open the target file for delete or branch/add even if these conditions exist.


Re-branch source on top of deleted targets
If the source file exists and the target file does not, Perforce normally opens the target file for branch/add unless the target file is a deleted file. Checking this option opens the target file for branch/add even if it is deleted.


Delete modified targets if source is deleted
If the ending revision of the source file is a deleted file, Perforce normally opens the target file for delete unless the target file has any revisions that have not themselves been integrated to the source file. Checking this option opens the target file for delete even if it has been edited.


Force re-integration if previously integrated
Normally Perforce doesn't open a target file for integrate if all of the source file revisions under consideration have already been integrated to it. Checking the "force re-integration" option makes theintegrate command open the target file for integrate regardless of previous integration history. When you submit the file, integration history between the two files will be effectively rewritten to reflect the most recent of the duplicate integrations.


Don't copy newly branched files to workspace
Normally target files opened for branch/add are created in your workspace. However, because the content of the new target files is the same as that of the source files, your workspace files are not required to create the new files in the depot. If you don't need copies of the newly branched files in your workspace—for example, you are branching a large codeline but you don't plan to do work in the new codeline yourself—use this option.


Change target filetype to match source
Normally, Perforce doesn't change the filetype of target files when you integrate to them. Each newly branched file is given a filetype that matches that of the file it was branched from. Subsequent changes to the source filetype will not affect the target file during integration unless you use this option. When you use this option, the filetype of each target file will be changed to match that of the corresponding source file at the revision you are integrating from. The filetype change takes effect when you submit the target files to the depot. (Note that you can also explicitly change the filetype of opened files before submitting them.)


Don't sync target files to head revision
Normally, Perforce automatically syncs to the head revision before integrating. If you select this option, Perforce uses the revision that you have in your workspace, instead of the head revision. Note that this is only true if your server is 2002.1 or newer.

http://www.perforce.com/perforce/r11.1/manuals/p4web/help/integrate.html

Tuesday, July 23, 2013

Running a Java app as a daemon on Linux

There are many ways to run a Java app on a Linux device. The problem is that normally when you log out, this app will stop executing. This is a problem when you want the execution to out-live the session.


A command that can solve this issue is nohup. This command will ensure that the execution does not stop when you logout. Also it will not block the terminal.

This is used like this:

nohup java -jar MyJar.jar &

Note :

What will not work is adding an ampersand behind the command. This would be like this:

java -jar MyJar.jar &

The reason for this is that even though this would not block the terminal, it is still tied to the current session. So once the session ends, it will stop executing.

Web Services and Java

A good framework to create a REST API in Java is JAX-RS.

The IDE I used for this project was Intelli-J.

Here is the link to how to get a basic Hello World of a JAX-RS project/





It is important to remember to bundle all the needed .jars in your application. Do this as explained here.

The output of this step should be a .jar file.
To run this, simply call

java -jar FileName.jar.

Friday, May 24, 2013

Best way to measure execution time in .Net

Sometimes you need to measure how long some code takes to run. This is useful for benchmarking or even comparison of different algorithms. There are three main ways of doing this.

The first one is by reading DateTime.UtcNow before you start and after you finish. This is quite fast, however its granularity is quite low (around 10ms.) If you want to measure something which takes less than that, simply run it thousands of times, and then divide by the number of executions.

The second approach is by using a StopWatch. You simply create a StopWatch object, call the Start() method, and then the Stop() method. Then read the Elapsed value. However this is known to be unreliable due to bugs in the BIOS on multi-processor systems. It is also time consuming in itself.

The third (and my favourite) way is by using Process.TotalProcessorTime.
You first call

TimeSpan start = Process.GetCurrentProcess().TotalProcessorTime;


and then

TimeSpan finish = Process.GetCurrentProcess().TotalProcessorTime;

This is the ideal way because it actually measure how long your process has made use of the CPU. However, it also has the worst performance.

Monday, April 8, 2013

Make connecting to various machines easy

If like me, most of your day is spent connected to various remote machines, there is a very nifty tool which can make your life very easy.

This tool is mRemoteNG.

This is a tabbled, multi-protocol, remote connections manager. It lets you store all your remote connections in one place, including passwords and favourite settings. It supports the following protocols:

  • RDP (Remote Desktop/Terminal Server)
  • VNC (Virtual Network Computing)
  • ICA (Citrix Independent Computing Architecture)
  • SSH (Secure Shell)
  • Telnet (TELecommunication NETwork)
  • HTTP/HTTPS (Hypertext Transfer Protocol)
  • rlogin
  • Raw Socket Connections


And what's even more awesome is that is is totally free, and open source!


This is what it looks like.


Monday, April 1, 2013

Unity3d Get Heap and Memory Size

Unity3d is a very powerful game engine. Underneath it makes use of the awesome Mono framework, which makes it possible for people to write video games using C#. How awesomer can things get?

Below is a code snippet that one can use to get the heap size and the used memory size.


#if UNITY_IPHONE && !UNITY_EDITOR
    [DllImport("__Internal")]
#else
       [DllImport("mono")]
#endif
static extern long mono_gc_get_used_size();  //Amount Used

#if UNITY_IPHONE && !UNITY_EDITOR
    [DllImport("__Internal")]
#else
       [DllImport("mono")]
#endif
       static extern long mono_gc_get_heap_size(); //Total Amount

long memUsed = mono_gc_get_used_size();
long deltaMem = memUsed - previousMemUsed;
long heapSize = mono_gc_get_heap_size();
float percentageMemUsed = (memUsed / (float)heapSize) * 100;
previousMemUsed = memUsed;



For more profiling, use these tools: http://docs.unity3d.com/Documentation/Manual/Profiler.html

Monday, February 4, 2013

Query Perforce MetaData

Sometimes you need to find out more data about your version control. For example how many people commit their work right before a deadline? Or how many commits did a particular user make? Or when did a commit with a particular description get checked in?

This is where the awesome tool P4Sql comes in handy.

First you need to download the P4Report: Reporting System from this location.
Then you need to install this package.
Once installed, you should open the P4Sql tool, normally found under C:\Program Files\Perforce\P4Report
Here you can query the schema of the database.
The schema can be found here.

Thus we can run queries such as

SELECT * FROM FILES WHERE REVISION = 23;

to see what files were changed in the revision, or

select * from changes where description like '%maya%' ;

to see what changes had descriptions that included the word maya.

To see the schema of Perforce, you can refer here.


Find Perforce deleted files

A big advantage of a version control system like Perforce, SVN or TFS is that you can safely delete code or even whole files, and then be able to retrieve them later.

When you are in Perforce there is a very easy way to show deleted files in your current Depot.

Simply choose Show Deleted Depot Files from the current filter as shown below.