Monday, December 29, 2014

windows start-script for applications

I wrote a WCF service (started as command line application) and had the problem that it needs to be started with admin privileges. So I wrote a dos-script that can either start the server and/or the client and checks the privileges in the first place. Writing a dos script was a little bit like time traveling for me, but finally I managed and understood it. Here my findings:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@echo off
echo _________________________________________________
echo.
echo            HERE A FANCY SERVICENAME
echo _________________________________________________
net session >nul 2>nul
if %errorLevel% equ 0 (
   echo Success: Administrative permissions confirmed.
) else (
   echo Failure: Current permissions inadequate.
   goto end
)
echo.
echo.
set /P startServer=Should the server be started? (y/n) 
set /P startClient=Should the client be started? (y/n) 

IF /I "%startServer%"=="y" (
  echo starting server
  start cmd /c "Server.exe"
) else (
  echo starting server skipped
)

IF /I "%startClient%"=="y" (
  echo starting client
  start cmd /c "Client.exe"
) else (
  echo starting client skipped
)

:end


  • line #1 calls a "hidden from dos-box" action (using @) and disables the printing of the actual commands (only the result of the call will be displayed, but not the call).
  • optionally here a title can be set (using dos: title FANCYNAME) or clearing the screen can be done using command cls
  • following lines show a header
  • then there is a little hack by calling net session. There is no need to understand what this command is doing. The only important information is, that it quits with error 5 (access denied) if you are not currently running in admin-mode. Standard output stream and error output stream will be redirected to nul (to nowhere), so that the only effect is that the errorcode is set to 5 (failed to call the application) or 0 (everything worked fine). 
  • line #7: The errorlevel is a pre-defined variable set by the return code of the previous application. (Unluckily I am not sure if successful applications always reset this variable properly to zero. If you want to be sure then use the command "set" to overwrite the value to zero).
  • the following shows success or error message and jumps on error to the label in line 32 what means that the script stops there.
  • echo. prints an empty row. echo without . shows whether the echo-ing is on or no (as disabled in line #1).
  • set /P requests the console to read from standard in and to write the result to the variable.
  • now we can check for the inputted values (/I for case-insensitive). The 2 equal-signs are similar to equ, but refer to text equality and not to numeric equality
  • start calls an application run in its own dos-box what is a metaphor for run asynchronously without checking the return value or %errorlevel%. I started an own command prompt and call the command with /c parmeter.
pitfalls: 
  • the brackets work exactly the way they were shown above. Separation to own lines are not only forbidden, the script simply doesn't work anymore. 
  • if the server needs some time to startup and the client should be called a few seconds later, then it is a good trick to use a ping localhost (normally 4 seconds for standard 4 packets) to "waste" some time. (start cmd /c "ping localhost >nul 2>nul && Client.exe) Another solution is the command "timeout" what seams appropriate to.

cheers,
Daniel

Tuesday, December 16, 2014

ASP.NET developer efficiency

... because I was asked how to develop asp.net faster... here my top 10 shortcuts which boosted my work (in vs-studio 2013 using the standard key mapping for c# developers)

  1. press ctrl + "," to move between files
  2. press f12 to go to definition
  3. press ctrl k+r for find all references
  4. press f8 to move in the list of found items
  5. press ctrl+shift+b to compile
  6. press ctrl + "-" to jump back in history (regarding cursor position)
  7. press ctrl + alt + p to attach to process (w3wp for iis hosted asp.net) and type the name of the process
  8. press ctrl + shift + f to find stuff / h to replace
  9. press ctrl + "." to add references, implement interfaces and stuff
  10. press alt+tab to jump to browser, f5 for refresh (sorry for mentioning that :-) ).

cheers, Daniel

Thursday, December 11, 2014

nullpointerexception - history

... because today my program won 1:0 against me by raising a nullpointerexception I was willing to check out who invented the null pointer.

So thank you Mr. Tony Hoare, thank you very much! Built in 1965 for "algol w".
His quote: "I call it my billion dollar mistake". 
I would advice him to count that in hours of searching and not in dollars...


kind regards,
Daniel

Tuesday, December 2, 2014

kill only connections of a concrete DB

Today I had the problem that in a dead-lock situation a colleague (responsible for a database on my db server) wanted to fix the situation himself. While using activity monitor he found out which process (more or less equals to connection) was responsible for the fault-situation and wanted to set up a kill statement.

For activity monitor he needed the rights ( http://msdn.microsoft.com/en-us/library/ms175518.aspx ):

  • VIEW SERVER STATE

    and
  • CREATE DATABASE, 
  • ALTER ANY DATABASE, or 
  • VIEW ANY DEFINITION 
Long story short he was not allowed to call kill and I was quite happy about it, because it makes sense that a data owner is not allowed to kill processes of other unrelated services. In fact to kill his own processes could also be accomplished by restarting the corresponding server application, so he seems to have some kind of power anyway. I liked to hear, that I hadn't have to get in touch with the process search, so I needed to enable process killing. My problem was how to secure the whole system against other kill requests and still offer the functionality. 

Some research later I found the concept of impersonation (execute as), but I couldn't imagine how. I tried to allow the user (who failed to kill processes) to switch its user context to a more privileged user. Nothing won, because he is still able to do what he likes. So I created a stored procedure which encapsulates this logic (-> security by obscurity... if you don't know you can switch, you wouldn't try it). Better, but not good enough, because the source of the stored procedure definition was readable, so it is easy to understand which execute as statements has to be executed to become privileged and a security issue (as good as worst case). I tried a lot using master DB, other schemas and so on and found in the end the following link.


... with 5 golden rules which in fact really worked for me. 

  1. We create a new database and set the TRUSTWORTHY flag on
  2. We create a login with the permissions we want
  3. Set the login as the owner of the new database
  4. We create a stored procedure that does the work we want within the new database.
  5. We add the EXECUTE AS OWNER clause to the SP
These were really good tips and finally it worked to impersonate the execution! I just had to hard code the database name which the executor is allowed to kill (in the following code snippet DBNAME1) and check whether the - now - reachable sysprocesses table has an entry with passed in spid and hard coded database.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
   if(  exists (select 
  * 
  from master.sys.sysprocesses sproc
  where db_name(dbid) = 'DBNAME1' and 
  sproc.spid = @kill_spid)) 
   begin
 
 print 'resolved as DBNAME1 connection ... connection will be killed';
 SET @KillStmt = 'kill ' + CAST(@kill_spid AS VARCHAR(50)) + ''
 PRINT @KillStmt
 
 EXECUTE(@KillStmt)

   end else begin
 
 print 'connection was not established to DBNAME1 ... request will be ignored';

   end

kind regards,
Daniel

Friday, November 28, 2014

UnitTesting with DateTime.Now

Today I needed to unit test a component which uses System.DateTime.Now (C# .NET) ...

The good answer:this actually works using System.Fakes (sorry, no idea in which edition, but in ultimate it works perfectly). In the past microsoft seemed to use "moles" (see: http://research.microsoft.com/en-us/projects/moles/ ) instead of "fakes".

Using fakes:

  • Create a Unit-Test Project
  • Select References
  • Right-Click on "add fakes assembly" 
    • this adds ref to "...Fakes.dll"
    • Fakes Folder with xml stuff
  • now you enabled fakes for system (most of the time mscorlib will be faked too by VS)... 
  • start to use it


Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
        [TestMethod]
        public void CheckCurrentDate_ResultFixed2012()
        {
            // Arrange
            using (ShimsContext.Create())
            {
                // Act
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2012, 12, 31);

                // Assert
                Assert.AreEqual(2012, DateTime.Now.Year);
            }
        }


Kind regards, Daniel

Thursday, November 6, 2014

Expression Trees: good ideas and bad ideas

Today I had a look at expression trees. There are some really cool solutions using expression trees, which make the world of developers a better place.

I focused on the usage in combination with PropertyChanged where we have a lot to do with constant ("magic") strings which refer to the calling property name. In standard WPF projects we put this RaisePropertyChanged - boiler plate code like in the example http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx in every setter of a property.

A new and modern possible solution as used in

is to work with expression trees. 


The concept is:
  • still use caller member name if possible
  • make a lambda function which has only 1 expression tree leaf: the property.
  • push the lambda function as parameter inside (as expression tree)
  • In the expression tree read the name of the property which is handed in and use its name as string like in the original way
The function to read the described expression tree is quite simple (as shown in http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression/2916344#2916344 ) . The following example code shows how it works:

1
2
3
4
5
6
        private string GetMagicString(Expression<Func<object>> exp) 
        {
         
            return (exp.Body as MemberExpression ??
                ((UnaryExpression)exp.Body).Operand as MemberExpression).Member.Name;
        }

Important here is:

The difference is that you will get a UnaryExpression if your expression represents a value type whereas you will get a MemberExpression if your expression represents a reference type.

So you can call GetMagicString(() => MyProp) and get back MyProp as string.

This is a good idea, because now you get a compile error if you mistype your input. Quite cool.

Attention! You can implement magic strings with expression trees too and have the same problem as mentioned before. 


1
2
3
            MessageBox.Show(
                PrintStaticInfo(
                    (machinename) => string.Format("{0} is the machine name", machinename)));

You see we use machinename as parametername and push this expression tree into method PrintStaticInfo.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
        private string PrintStaticInfo(Expression<Func<string,string>> expression)
        {
            string value = string.Empty;
            switch (expression.Parameters[0].Name.ToLower())
            {
                case "username":
                    value = Environment.UserName;
                    break;
                case "machinename":
                    value = Environment.MachineName;
                    break;
            }
            return expression.Compile()(value);
        }

This function inserts the value for a given parameter by name. The parameter name if mistyped breaks exactly the same way as PropertyChanged does if the wrong property name was inserted. Ugly code, different ways :-).

kind regards, Daniel

Wednesday, October 22, 2014

Regex in sql server

The like statement is sometimes a bit frustrating, because it has nothing to do with the regular expression you know from development in e.g. .NET. Similar to like is patindex.

The proprietary placeholders are:

  • % for 0-n characters
  • _ for 1 character
  • [] ranges
    • e.g. [a-f] for any single character between a and f inclusively
    • e.g. [abcdef] for any single character between a and f inclusively
    • e.g. [[] for [, - can be set as first item in list to use it, []], [_], [%]
  • [^] ranges (any character which is not in the range.

Really using Regex:
  • VBScript, COM
    http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx
  • Project for native regex
    http://www.codeproject.com/Articles/4733/xp-pcre-Regular-Expressions-in-T-SQL
  • CLR function
    http://msdn.microsoft.com/en-us/magazine/cc163473.aspx
    http://msdn.microsoft.com/en-us/library/w2kae45k%28v=vs.80%29.aspx

kind regards,
Daniel


EDIT: in contrary to mysql ... there you can use it in the where statement "native". E.g.:
select * from xyTable where name regexp 'asdf$' 

Monday, October 20, 2014

fill gaps of an identity column

I found out that it is possible to fill gaps in an identity table without reseeding the table ( http://msdn.microsoft.com/en-us/library/ms176057.aspx ).

You can "set identity_insert" option to on to set the values directly ( http://msdn.microsoft.com/en-us/library/ms188059.aspx ).

But:

  • only 1 Table can have this setting on
  • If value inserted > the current identity value for the table -> automatically uses the new inserted value as the current identity value.
kind regards,
Daniel

Thursday, October 16, 2014

Tuesday, October 7, 2014

design data in wpf (best practise)

I used to have a DB connection in my wpf applications which will be set from outside so that the application has no idea what the connection string could be. The result is, that I start my application development without any design data.

What is nice here is that you can check whether you are in design mode or not and set the connection string. Therefore check:

http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.getisindesignmode.aspx

... but in fact, I really don't like that solution because it works only if you have wpf references in the project what a DB-access layer typically doesn't have. Pushing the connection string from the ui-layer to the business logic layer and then to the dbaccess-layer for design makes it a mess (spaghetti code). Moreover you need a database connection even at design time to work on the ui, what can be painful too.

I found my solution inside the following msdn blog post with some additional brain work:

http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/sample-data-in-the-wpf-and-silverlight-designer.aspx

I would recommend in a MVVM pattern UI to set the datacontext to the VM and set d:DesignData right afterwards to a child class of that class.

so e.g.: a grid's data context is bound to a class called something like MainWindowViewModel and d:DataContext (as described at the msdn article) is bound to something like MainWindowViewModelDesignData.

The ...DesignData should inherit from the base view model and initialize the properties with hard coded design data values (or maybe xml files which are always available on hard drive). I would recommend to set extreme values (min/max values) inside the view model or even better prepare more than one vm-designdata class (or what I would do: put in a switch which can be modified quickly), because it is much easier to change the desing data, compile, close and open the window than to compile, start, prepare test data, check, prepare other test data, check,... and so on. The design data is giving you a perfect overview how the ui would look like and is a perfect solution to test your ui about extreme values entered by the user (e.g.: a login name can have 7 to 50 characters: make cases with a) only 7 char logins, b) only 50 char logins and c) a mix with even 25 char logins).

This worked fine for me. Please let me know if you see it differently.

kr, daniel

EDIT:

today (about a month later) I used the mvvm light framework which is shipped with a dependency injection service, where view-models are registered. With mvvm light it is even easier to register design data in design mode.

Service-Locator code:


1
2
3
4
5
6
7
8
            if (ViewModelBase.IsInDesignModeStatic)
            {
                SimpleIoc.Default.Register<MainViewModel, MainDesignViewModel>();
            }
            else
            {
                SimpleIoc.Default.Register<MainViewModel>();
            }


kind regards, Daniel

Saturday, September 20, 2014

Persistence framework

Today I am looking for a persistence framework for c#. This is hard because I don't need an OR-Mapper. I need something where I can put in an object and it stores it to database or (and that is the hard thing to find) to an isolated storage or file system.


I found the following list:
   http://csharp-source.net/open-source/persistence


This list is rather disappointing (even if in google top ranked) because most of the projects in here are dead. Some admit, some don't. What I really dislike on this list is that even code generators which will manage the access logic are listed as persistence frameworks. I think they aren't.

Still one of the best solutions are:
- mybatis (only "object to DB" mapping): https://code.google.com/p/mybatisnet/
- Habanero (ORM, but also standard UIs): http://www.chillisoft.co.za/habanero/
- SPF (persistence framework, but only for DBs): http://sisyphuspf.sourceforge.net/home.htm

..and yes of couse, I will not forget to mention NHibernate ( http://nhforge.org/Default.aspx/ ).

Tuesday, September 16, 2014

Document your code, what's next?

Today I have been working on my release version of my project. 

Releasing a project means to me that
  • the features are developed
  • the features are tested
  • the database was adapted
  • the code is re-factored
  • the code is styled
    ... and last and worst
  • the missing comments (I left to the end as always) are added.

To check style and comments I use the tool "StyleCop" which is quite cool but also a pain in the ... hmmm,... neck. This means that at least all summary tags are filled out. After some routine you don't even think of the benefit of doing this. So what is the benefit of the summary tags (and of course there are a lot more tags to mention like the value, returns, param,...)?

In the msdn description of the summary tag ( http://msdn.microsoft.com/en-us/library/2d6dt3kf.aspx ) first of all the object browser window is mentioned, but I don't think that this is THE benefit for most developers. In fact I use the object browser window as good as never... or let's say never.

The article also mentions documentation tools like sandcastle (what is a bad example, because the project is no longer under active development by microsoft ... see http://sandcastle.codeplex.com/ ... even if there is a new open source branch of the project http://shfb.codeplex.com/ ). This project is much too complicated for me. I would like to generate a damn easy chm-file or something which looks great and what makes no troubles at all. 

There are commercial product which seemed to accept my challenge of "creating an easy to use tool" like 
  • vsdocman ( http://www.helixoft.com/vsdocman/overview.html ) or 
  • document X! ( https://www.innovasys.com/product/dx/features_vsnet.html ) or 
  • live documenter ( http://livedocumenter.com/ ) 
did. Other open source project seemed to make a complicated task ( generating a documentation ) more or less impossible (like doxygen). An other approach is to simply provide an xslt file to the generated xml-documentation (out of visual studio).

Finally I decided to use the github project docu ( http://docu.jagregory.com/ ). I downloaded the source, compiled it and it simply worked. I don't really like the template, but this is customizable, so hurray ... I found a solution which generates static and simple web pages. These pages can be opened from inside the visual studio (even if this solution is not yet perfect) using ctrl w + w.

cheers,
Daniel

Sunday, September 7, 2014

Write a great research paper

Hi,

I got a hint about a good youtube video about Professor Simon Peyton Jones, Microsoft Research:

https://www.youtube.com/watch?v=g3dkRsTqdDA


It is about 7 tips of how to write a good research paper (but there are about a hundred more in the video inside of the hints):

- #1 Don't wait: write 0:21
- #2 Identify your key idea 4:16
- #3 Tell a story 7:20
- #4 Nail your contributions to the mast 9:34
- #5 Related work 16:44
- #6 Put your readers first 23:50
- #7 Listen to your readers 28:42

I would highly recommend that video ...

kind regards,
Daniel

Friday, September 5, 2014

Link-List

Hi,

I found a cool list of books and links:

- https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md


I will add items to the list if I find something similar...

cheerio,
Daniel

Tuesday, July 15, 2014

app domains

Hi,

today I wanted to create a launcher application to launch my other wpf applications. This sounds easy but is really hard because you can have only 1 application object in an application domain. The task to do seemed to be clear... I needed a second application domain. But first I researched a little bit about application domains and want to show here some quotes to this:

Operating systems and runtime environments typically provide some form of isolation between applications. For example, Windows uses processes to isolate applications. This isolation is necessary to ensure that code running in one application cannot adversely affect other, unrelated applications.
Application domains provide an isolation boundary for security, reliability, and versioning, and for unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.
http://msdn.microsoft.com/en-us/library/cxk374d9.aspx
AppDomains best visualized as a very light weight process.
There can be N AppDomains per .Net Process but generally speaking there is only one. The real advantage of AppDomains is they provide an isolation boundary within your process. Objects can only talk to each other across an AppDomain boundary via remoting or serialization.
It's also possible to run 2 AppDomains at completely different security levels within a process. This can allow you to run your main application at Full Trust while running Untrusted Plugins at a much lower trust level.
It's hard to blanket say yes or no to whether or not a thread respects an AppDomain. It's possible for a single thread to be in N different AppDomains. Such a situation is possible if an object in one AppDomain makes a remote call to an object in another AppDomain. The thread will have to transition between the AppDomains in order to complete.
The disadvantage of AppDomains is mainly complexity. Remoting can take a little bit of time to get your head around and properly setting up an AppDomain can be a non-trivial process.
You may want to take a peek through the MSDN documentation on AppDomains. It's hard to find a sucint tutorial that describes them because they have a variety of complex features. This provides a nice overview which if it doesn't answer your question directly will at least point you in the right place.
http://stackoverflow.com/questions/622516/i-dont-understand-application-domains by JaredPar

JaredPar's answer is good, except he doesn't note the raison d'etre for AppDomains - which is that you can only UNLOAD an Assembly by unloading its AppDomain. If you are a long-running OS process, and you expect to have to load and then later unload assemblies for whatever reason then you need an AppDomain. The prototypical example here is ASP.NET, which loads app code assemblies on demand and then can unload them later, when the apps are no longer being actively used.
The cost you pay for the ability to unload is that independence - you need to communicate across the AppDomain boundary, Can't make a simple method call. You need to manage the AppDomain lifecycle. Etc.
If you just need to dynamically load Assemblies and don't think you'll need to unload them during the life of a single process then you probably don't need to run multiple AppDomains. A good example here might be a rich app that supports a plug-in model, where it sniffs out plug-in assemblies in a "etc" directory and loads 'em all up. However, if the plug-in model calls for unloading the plug-ins ... well.
There are outlyer scenarios. Like, suppose you want to load 2 different versions of an Assembly at the same time. You can run into pitfalls if you don't segregate them with AppDomains. But that will be fairly rare.
The core scenario that justifies the existence of AppDomains is the long running process that must be able to unload assemblies.
Of course, applications could rely on the OS process when you want to unload an assembly. In other words, you could have 3 or 4 cooperating processes running, each with its own set of Assemblies, and when you want to unload an assembly, just shut down the process that hosts that assembly. But the AppDomain offers a higher-perf mechanism to do that, without requiring process stop/start or cross-process comms, which is heavier still than the cross-AppDomain comms described previously. I mean it's still remoting but it is slower and more context switching.
http://stackoverflow.com/questions/622516/i-dont-understand-application-domains by Cheeso

and now a solution how to run more appdomains in C#. ( http://blog.lab49.com/archives/2355 )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;
using System.Threading;
 
namespace WPFDomainLab
{
  class Startup
  {
    [STAThread()]
    static void Main()
    {
      var domain1 = AppDomain.CreateDomain(
        "first dedicated domain");
      var domain2 = AppDomain.CreateDomain(
        "second dedicated domain");
 
      CrossAppDomainDelegate action = () =>
      {
        Thread thread = new Thread(() =>
        {
          App app = new App();
          app.MainWindow = new Window1();
          app.MainWindow.Show();
          app.Run();
        });
        thread.SetApartmentState(
          ApartmentState.STA);
        thread.Start();
      };
 
      domain1.DoCallBack(action);
      domain2.DoCallBack(action);
    }
  }
}

please consider to use LoaderOptimization property... (here I would suggest to delete the app file and create your own, because the real main method is hided in the app.g.cs file by the visual studio).

For starting a wpf application it is neccessary to create a domain and then to call


1
newdomain.ExecuteAssembly(path); 

and in a finally block to call:

1
AppDomain.Unload(newdomain); 

What is quite cool in this solution is to be able to pass in some parameters. This communication works over:
 
1
newdomain.SetData(name, valueObject);


Kind regards,
Daniel

Tuesday, July 8, 2014

SSIS Repository

Hi,

today I am working with SSIS and tried to find some 3rd party tasks.

I found the page:

   http://ssisctc.codeplex.com/

It is also a good reference how to build your own SSIS task because some are open source. I will try to build my own soon...

kind regards,
Daniel

Wednesday, June 11, 2014

xp_cmdshell in sql server

Hi,

today I got a request to enable xp_cmdshell on my sql server because an application needed the functionality to list the content of a directory out of a t-sql stored procedure.

The functionality is pretty old (already supported by sql server 2000), but evil referring to sql server security blog entry: http://blogs.msdn.com/b/sqlsecurity/archive/2008/01/10/xp-cmdshell.aspx

If security context is not set with caution enabling this setting enables a user to access a command line to the server with administrator rights. This is bad. (Default is to access the command line with the security context of the sql server service account, but it can be changed to other credentials using: sp_xp_cmdshell_proxy_account )

Syntax:
xp_cmdshell { 'command_string' } [ , no_output ]


Enabled the feature:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
reference: http://msdn.microsoft.com/en-us/library/ms190693.aspx

Check if it is turned on or off:
1
2
3
4
5
6
7
SELECT 
   name AS [Configuration], 
   CONVERT(INT, ISNULL(value, value_in_use)) AS [IsEnabled]
FROM  
   master.sys.configurations
WHERE  
   name = 'xp_cmdshell'
reference: http://sqltidbits.com/scripts/check-if-xpcmdshell-enabled-across-multiple-servers

... and here an example how it can be used (found in the web):
1
2
3
4
5
6
7
8
9
create table #tmp(result varchar(255))
insert into #tmp exec master.dbo.xp_cmdshell 'ping yahoo.com'
 
if exists(select * from #tmp where result like '%request timed out%')
 print 'timeout'
else
 print 'reply'
 
drop table #tmp
references: http://www.nullskull.com/q/11008/xpcmdshell-output.aspx

and even better:

1
2
3
4
5
6
declare @results table(result varchar(255))

insert into @results
exec sp_executesql N'xp_cmdshell ''ping www.yahoo.com'''

select * from @results
reference: http://stackoverflow.com/questions/1842126/call-tracert-and-ping-from-sql-and-put-the-result-in-sql-table

kind regards,
Daniel

Tuesday, June 10, 2014

creating objects dynamically c#

Hi,

today I am writing on my term paper and I needed a way to create objects dynamically while having a type object.

I tried the old-school way as following:

1
2
var x = typeof(List<string>).GetConstructor(
   new Type[] { }).Invoke(new object[] { });

and got my expected result. This was kind a hard way but it worked as it did 10 years ago.

My problem was now: I knew that the object to create is List, but wanted to have string dynamically passed in by a parameter or generic into my function. I found the following solution after about an hour of googling:


1
2
var y = Activator.CreateInstance(
                typeof(List<>).MakeGenericType(typeof(string)));

MakeGenericType does the trick. Using activator is not necessary, but seems to be much easier to use and perfect for my use case. With shame I have to admit that Activator seems to exists since .NET framework 1.1 (= 2003). Anyway, I love it.

Kind regards,
Daniel

Thursday, May 29, 2014

disconnect all users from db

Hi,

it is often necessary to disconnect all open connections from a database (e.g.: if you want to delete it or take it offline). Management Studio has a checkbox to kill all connections in most of the cases where it makes sense. This is not so helpful if we want to script our stuff, so the following code suggests a way to kill all connections. (I found 90% of this piece of code on the web as a code snippet, but I forgot where... sorry for not mentioning the original source)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Declare @dbname sysname

Set @dbname = 'db'

Declare @spid int
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname)
While @spid Is Not Null
Begin
        Execute ('Kill ' + @spid)
        Select @spid = min(spid) from master.dbo.sysprocesses
        where dbid = db_id(@dbname) and spid > @spid
End

the only open task to execute this script is to enter the name of the db you want to disconnect the user from and enter it instead of the value db in the @dbname variable.

Kind regards,
Daniel

Wednesday, May 28, 2014

find colors for a style sheet

Hi,

today I needed some colors to build a website (or in detail to build a css style sheet).

The following pages supported me much while choosing matching colors:

- https://kuler.adobe.com
- http://colorschemedesigner.com/

Kind regards,
Daniel

get inserted id of identity column

Hi,

a situation I am always confronted with is: insert into a table, get this damn auto generated value to work with it. I don't know any database independent solution (except of using the max id inserted, what can be ok in some cases, but can fail too).

In sql server I found a solution for this problem at technet: http://technet.microsoft.com/de-de/library/ms190315.aspx ... this page describes a stored function which returns exactly the value we need (some kind of magic happens here).

The (filtered) example of technet:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
CREATE TABLE TZ (
   Z_id  int IDENTITY(1,1)PRIMARY KEY,
   Z_name varchar(20) NOT NULL);

INSERT TZ
   VALUES ('Lisa'),('Mike'),('Carla');

-- inserts 1,2,3

INSERT TZ VALUES ('Rosalie');

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];

-- returns 4


Kind regards,
Daniel

Column Panel

Hi,

today I wanted to arrange my elements in a grid in another way than stackpanel does. So I started to search for panel-implementations and found a simple implementation for a radial panel. Unfortunately a radial panel was not the solution for my problem so I had to build it myself. To tell the truth: it is even easier than I thought.

Panel
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace ColumnPanelProject
{
    public class ColumnPanel : Panel
    {
        #region ColumnsCount

        public int ColumnsCount
        {
            get { return (int)GetValue(ColumnsCountProperty); }
            set { SetValue(ColumnsCountProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ColumnsCount.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ColumnsCountProperty =
            DependencyProperty.Register("ColumnsCount", typeof(int), typeof(ColumnPanel), new PropertyMetadata(0));

        #endregion

        private readonly Size InfinitySize = new Size(double.PositiveInfinity, double.PositiveInfinity);
        
        protected override Size MeasureOverride(Size availableSize)
        {
            
            foreach (UIElement child in Children)
            {
                child.Measure(InfinitySize);
            }

            return base.MeasureOverride(availableSize);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            if(this.Children.Count > 0)
            {            
                int columns = this.ColumnsCount != 0 ? 
                                this.ColumnsCount : 
                                (int)(finalSize.Width / Children[0].DesiredSize.Width) ;

                int x = 0;
                int y = 0;

                foreach (UIElement child in Children)
                {
                    child.Arrange(new Rect( x * child.DesiredSize.Width,
                                            y * child.DesiredSize.Height, 
                                            child.DesiredSize.Width, 
                                            child.DesiredSize.Height));

                    x = (x + 1) % columns;
                    y = y + (x == 0 ? 1 : 0);
                }
            }

            return finalSize;
        }
    }
}

Window
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<Window x:Class="ColumnPanelProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ColumnPanelProject"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="456.579" Width="481.579"
        >
    <Window.Resources>
        <System:Int32 x:Key="columnCount">0</System:Int32>
        <ItemsPanelTemplate x:Key="columnTemplate">
            <local:ColumnPanel ColumnsCount="{DynamicResource columnCount}" />
        </ItemsPanelTemplate>

        <DataTemplate x:Key="dataTemplate">
            <Grid Margin="3" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center">
                <Border BorderThickness="5" BorderBrush="LightGray" CornerRadius="10">
                    <TextBlock TextWrapping="Wrap" Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
                </Border>
            </Grid>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>

        <ItemsControl
            Grid.Column="0"
            Grid.Row="0"
            Grid.ColumnSpan="2"
            ItemsSource="{x:Static Member=local:MainWindow.MyItems}"
            Name="itemsControl" 
            ItemTemplate="{DynamicResource dataTemplate}" 
            ItemsPanel="{DynamicResource columnTemplate}" Margin="0,2,0,-2" 
            />
        <Label Grid.Row="1" Grid.Column="1" Content="{DynamicResource columnCount}" HorizontalContentAlignment="Center" />
    </Grid>
</Window>

Code-Behind
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ColumnPanelProject
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static ObservableCollection<string> myItems = null;

        public static ObservableCollection<string> MyItems
        {
            get
            {
                if(myItems == null)
                {
                    myItems = new ObservableCollection<string>();
                    (new[]{
                        "Dr. Leonard Leakey Hofstadter",
                        "Dr. Dr. Sheldon Lee Cooper",
                        "Penny",
                        "Howard Joel Wolowitz",
                        "Dr. Rajesh „Raj“ Ramayan Koothrappali",
                        "Dr. Bernadette Maryann Rostenkowski-Wolowitz",
                        "Dr. Amy Farrah Fowler",
                        "Stuart Bloom"}).ToList().ForEach(x => myItems.Add(x));
                }

                return myItems;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

This article should show how a grid arrangement can be set up using only MeasureOverride / ArrangeOverride.

referring to msdn MeasureOverride should implement:
  • Iterate your element's particular collection of children that are part of layout, call Measure on each child element.
  • Immediately get DesiredSize on the child (this is set as a property after Measure is called).
  • Compute the net desired size of the parent based upon the measurement of the child elements.
The return value of MeasureOverride should be the element's own desired size, which then becomes the measure input for the parent element of the current element. This same process continues through the layout system until the root element of the page is reached.


ArrangeOverride is obviously responsible for the arrangement of the items.


A good related article can be found here: http://drwpf.com/blog/2009/08/05/itemscontrol-n-is-for-natural-user-interface/


Kind regards,
Daniel

Tuesday, May 13, 2014

catch uncaught exceptions c# wpf

Hi,

today I heard about a solution to catch exceptions globally in C# with WPF:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            DispatcherUnhandledException += App_DispatcherUnhandledException;
        }

        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show("error");
            e.Handled = true;
            this.Shutdown(1);
        }
    }

This snippet handles ALL exceptions which are not caught, shows the message "error" and quits with error.

Kind regards,
Daniel

Friday, May 9, 2014

how to check the size of my database...

Hi,

I had the problem that my databases grow and I had no idea why... (in the end I found out that it was a badly developed function, but this article will focus on the way to find the item which is growing...)

My entry point was an error on my sql server. (The agent sends me errors with severity > 16 by mail, so the real entry point was the mail. I double checked the error after the mail using xp_readerrorlog). The error indicated that it was not possible to store any data to the disk, because it was full (what is bad).

To get the information which folder is the bad guy in this scenario I used a freeware tool called tree-size. It did exactly what I needed. The tool shows which folder takes which amount of data in percent. ( download page e.g.: http://www.chip.de/downloads/TreeSize-Free_13001595.html ) I was lucky because the data folder of my database showed up as the folder that took 90% of the storage. Even more luckily I found the mdf file (database file) of a specific database which showed up as the problem.

Next step was to make some space and restart my database (I'm not sure if this is an optional step or not, but I would always do that) and to stop my corresponding application. I connected to the database and wanted to know how space usage looked like. So I called (after some minutes of google-ing)

sp_spaceused

the result was the information about the current database... and with the first parameter I can check my table (select * from sys.tables shows a list of tables, so I can use: sp_spaceused 'mytablename'). Now I needed a trick to evaluate all tables (and to evaluate them in only one record set to filter them)... and here it is:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
CREATE TABLE #tmp
(
ID INT IDENTITY(1,1)
,name NVARCHAR(75)
,rows INT
,reserved NVARCHAR(50)
,data NVARCHAR(50)
,index_size NVARCHAR(50)
,unsed NVARCHAR(50)
)
INSERT INTO #tmp
   EXEC sp_MSforeachtable 'EXEC sp_spaceused ''?'''
SELECT * FROM #tmp
DROP TABLE #tmp

the result of this statement is list of tables with their corresponding information. One of these entries took 90% of the whole space. This was the entry to concentrate on...


how sp_spaceused can help me:

sp_spaceused shows a list of tables and indexed views. Used without parameters the output shows 2 result sets:
- general database level: name, size, unallocated space (<-- see shrink databases)
- general data info: reserved, data, index_size, unused

used with parameter (object name):
- table level: name, rows, reserved, data, index_size, unused

second parameter indicates whether the data should be recalculated or not (@updateusage).




kind regards,
daniel

Tuesday, May 6, 2014

source code beautifier hilite.me

Hi,

today, I found (or unfortunately it is already yesterday) a cool web-page that renders inserted source code to html code as highlighted content. It is a very simple solution to paste code e.g.: to blogger ... (I already used it in my last post.) ... for me it worked perfectly, because it supports the code-languages I use and multiple themes like e.g.: Visual Studio theme.

page-description:

hilite.me converts your code snippets into pretty-printed HTML format, easily embeddable into blog posts, emails and websites.

Just copy the source code to the left pane, select the language and the color scheme, and click "Highlight!". The HTML from the right pane can now be pasted to your blog or email, no external CSS or Javascript files are required.

hilite.me

kind regards,
Daniel

super simple event bus C#

Hi,

today I thought about how to decouple parts of my application. With decoupling I at first thought about a manager which dynamically loads modules and then uses their output to feed a following module... not quite flexible if you more or less "pipe" one part after another and then just chain their results (like in a LINUX-bash command call e.g.: "ps -aux | grep vi" where a manager calls first ps and then grep).

A better approach is to let a global instance store the data when it appears and then push it dependent of the use case to the module which needs it (application #1 lists its errors -> manager pushes it to the log manager -> write to log). This brought me to a big question: Do I need a coordinator if the software parts can talk between each other?

As usual the answer is "it depends". A manager or coordinator is e.g.: OK if you have a main system like notepad++ and you want to load add-on functionality to use another output formatter. Let the modules talk between each other if e.g.: you separate the business logic in independent parts (divide and conquer), but on the same level (not as master-slave).

For my application the communication of the software parts seems to look good. Now I asked myself how to communicate inside of an application (and still as a condition: decoupled). Middleware is over sized for a single application. Message queues or messaging in general seems over sized too. Eventbus was over sized in the first place too, but here google came in the game. I google-d different kinds of event buses and found awesome solutions. Open source and commercial. Big libraries and light-weight solutions. Then I found a very inspiring post of trystan ( http://trystans.blogspot.co.at/2012/01/simplest-eventbus.html / http://trystans.blogspot.co.at/2012/01/simplest-typesafe-eventbus.html ).

I decided to use an own event bus. The following code shows the basic idea (an event bus based on the version of trystan's blog). I decided to build the event bus system more like the .Net's event system using EventHandler and EventArgs and call an event by name.

My code follows below... it is still a basic solution, but it worked for me.

kind regards,
Daniel

BusEventArgs.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventBus
{
    public class BusEventArgs : EventArgs
    {
        public BusEventArgs(object value = null)
        {
            Value = value;
        }

        public object Value { get; private set; }

        public static BusEventArgs Empty = new BusEventArgs();
    }
}

EventBus.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventBus
{
    public static class EventBus
    {
        private static Dictionary<string, List<EventHandler<BusEventArgs>>> handlers
            = new Dictionary<string, List<EventHandler<BusEventArgs>>>();

        public static void Publish(string eventName, BusEventArgs e)
        {
            Publish(null, eventName, e);
        }

        public static void Publish(object sender, string eventName, BusEventArgs e)
        {

            foreach (EventHandler<BusEventArgs> handler in handlers[eventName])
            {
                handler(sender, e);
            }
        }

        public static void Subscribe(string eventName, EventHandler<BusEventArgs> handler)
        {
            if (!handlers.ContainsKey(eventName))
            {
                handlers.Add(eventName, new List<EventHandler<BusEventArgs>>());
            }
            handlers[eventName].Add(handler);
        }
    }

}

Tester.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EventBus
{
    class Program
    {
        public static object locker = new object();

        public static bool IsStoped;

        static void Main(string[] args)
        {
            Thread raiser = new Thread(() => Raise());
            Thread listener = new Thread(() => Listen());

            raiser.Start();
            listener.Start();

            Console.ReadLine();
        }

        private static object Listen()
        {
            IsStoped = false;

            EventBus.Subscribe("onRaise", (sender, e) => WriteRaised());

            while (!IsStoped)
            {
                Thread.Sleep(100);
            }
            Console.WriteLine("finished");

            return null;
        }

        private static object WriteRaised()
        {
            Console.WriteLine("raised");
            IsStoped = true;
            return null;
        }

        private static object Raise()
        {
            Thread.Sleep(5000);
            EventBus.Publish(new object(), "onRaise", new BusEventArgs());

            return null;
        }
    }
}

Wednesday, April 30, 2014

variable count of parameters in a t-sql stored procedure (sql server)

Hi,

yesterday I faced the problem that I had to push a variable amount of parameters in a stored procedure. In C# we have a keyword called "params".

public void MyFunction(params int[] myIDsToPush)
{
}

and call it like this:  MyFunction(1, 2, 43);
        
I expected that the database supports such a concept too, especially sql server, but unfortunately that was not the case :-( . I needed a work around. 

It took some time to think about possible solutions (and yes of course some google research too) but finally I realized that I needed a memory to store the data and even if no array type was available or params option another memory was necessary. Then I thought about (object to string -) serialization and how serialization can help to pass the items to the stored procedure.

So I built the following algorithm which deserializes ids from a string to a table (idstring represents the parameter, idtable is the result table).



 -- render a comma separated list of IDs into a table
 -- this targets on identity columns
 -- input string
 declare @idstring nvarchar(max) =
  '1,2,3,4,5,6,7,8,9,10,11,12,9999,13,752268687,100,56,322223,5'

 -- output object
 declare @idtable Table(id int)
 -- object to work on
 declare @parsedID   int = 0

 -- iteration variable
 declare @i   int = 0
 -- sign to work on
 declare @c   nvarchar(10)
 -- walk over
 while(@i <= len(@idstring))
 begin
  -- query sign to work on
  set @c = substring(@idstring, @i, 1);

  if(@c = ',')
  begin
   insert into @idtable values (@parsedID)
   set @parsedID = 0;
  end else if(ISNUMERIC(@c) = 1) begin
   set @parsedID = @parsedID * 10 + (cast(@c as int));
  end;
  -- increment iteration variable to walk over next item
  set @i = @i + 1;
 end;
 if(@parsedID <> 0) begin
  insert into @idtable values (@parsedID)
 end;
 select * from @idtable



kind regards,
Daniel

EDIT: found more or less my solution in a technet article (2002) https://technet.microsoft.com/en-us/library/aa496058(v=sql.80).aspx

Tuesday, April 22, 2014

PowerShell - how to start

Hi,

today I am working with power shell and I had no clue :-( so I checked out how to get information about the commands themselves. I found the following commands:

  • Get-Help
    shows the help of the get-help command. Adding a command name as argument shows the help of the command in the current context: e.g.: get-help get-childitem.
  • Get-Command
    shows all commands provided. First argument provides a possibility to filter. e.g.: get-command *-service shows all commands with the end "-service".
  • Get-Member
    shows what items were pipelined out from the last statement e.g.: get-childitem | get-member ... you can see that .NET's System.IO.{File|Directory}Info objects were pushed into the pipeline using get-childitem.
  • Get-help about_*
    shows all entries which are help to power shell concepts.
The setup of a command is "verb"-"dash"-"singular noun" like in get-childitem, so it is easy to split commands with the dash e.g. if searching for commands for "*-servi*". (Power shell is not case-sensitive)
 
What is another cool feature is the -WhatIf and the -Confirm option which is a inherited property (meaning all items where it makes sense have that option). Every item must have implemented -WhatIf parameter if its execution effects the state of the machine 
e.g.: Remove-Item test.txt -WhatIf DOES NOT remove the file, but what it does is telling the user what would have been done, if -WhatIf wouldn't be set...

Remove-Item test.txt -WhatIf
What if: Performing the operation "Remove File" on target "PATHPATHPATH\test.text".

The confirm option (quite boring against whatif) asks if you are really really sure to do whatever you wanted to do. You can set both preferences by changing $WhatIfPreference or $ConfirmPreference.


... but for me as a starter I use the commands I know by heart e.g.: del instead of remove-item... this seems to be so natural for me and makes it much easier to use power shell as a newbe. I was interested what del does and I found out (using get-alias) that this is mapped to Remove-Item too. So dear power shell developers: aliases were a perfect idea :-). Even dir AND ls works. Power shell seems to be very useful! I am looking forward to learn some more.

kind regards,
Daniel