Vitaly Dilmukhametov

  Home  |   Contact  |   Syndication    |   Login
  18 Posts | 0 Stories | 75 Comments | 0 Trackbacks

News

Archives

Post Categories

Good stuff

Tuesday, December 25, 2012 #

I just found an interesting behaviour of Windows Phone 7 TextBox default template. When TextBox is disabled, inner text is rendered with margin:

image

To reproduce it, create new Silverlight WP application and add following XAML inside default grid named “ContentPanel”:

<StackPanel Margin="0,12,0,0"> 
    <StackPanel.Resources> 
        <Style TargetType="TextBlock"> 
            <Setter Property="Margin" Value="25,0,25,0"/> 
        </Style> 
        <Style TargetType="TextBox"> 
            <Setter Property="Margin" Value="33,0,13,0"/> 
        </Style> 
    </StackPanel.Resources>
 
    <TextBlock Text="Name:" /> 
    <TextBox Text="some test text" IsEnabled="False" />
 
    <TextBlock Text="E-mail:"/> 
    <TextBox Text="test@movaxbx.com" InputScope="EmailNameOrAddress" /> 
</StackPanel>

The reason is that in disabled state TextBox’s control template is described using another TextBox:

 

<Border x:Name="EnabledBorder" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Margin="{StaticResource PhoneTouchTargetOverhang}" > 
    <ContentControl x:Name="ContentElement" BorderThickness="0" Padding="{TemplateBinding Padding}" 
            HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Margin="{StaticResource PhoneTextBoxInnerMargin}"/> 
</Border> 
<Border x:Name="DisabledOrReadonlyBorder" Visibility="Collapsed" Background="Transparent" BorderBrush="{StaticResource PhoneDisabledBrush}" BorderThickness="{TemplateBinding BorderThickness}" Margin="{StaticResource PhoneTouchTargetOverhang}" > 
    <TextBox x:Name="DisabledOrReadonlyContent" Text="{TemplateBinding Text}" Foreground="{StaticResource PhoneDisabledBrush}" Background="Transparent" 
            SelectionBackground="{TemplateBinding SelectionBackground}" SelectionForeground="{TemplateBinding SelectionForeground}" 
            TextWrapping="{TemplateBinding TextWrapping}" TextAlignment="{TemplateBinding TextAlignment}" IsReadOnly="True" Template="{StaticResource PhoneDisabledTextBoxTemplate}" 
            FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" FontWeight="{TemplateBinding FontWeight}" FontStyle="{TemplateBinding FontStyle}" /> 
</Border>

 

This XAML is a part of TextBox’s default control template (you can get full version with Blend). In case of setting IsEnabled=”False”, EnabledBorder is hidden and DisabledOrReadOnlyBorder is visible. So, textbox rendered using TextBox.

You can notice, that in first code sample style for TextBox without x:Key. It means, that style applied to any of child TextBox. So, margin was applied to control template’s inner TextBox too. And that’s the reason, why we have a shifted text in disabled state!

As a solution: you can add x:Key for TextBox style and apply it manually to every TextBox. In this case disabled state will work normally.

 

P.S. The same is valid for PasswordBox too.


Friday, September 2, 2011 #

I use JetBrains ReSharper tool for a long time – it’s a very useful thing, that can help me to be more efficiently.

 

Some time ago James Kovac made a training course for Pluralsight about everyday usage of ReSharper. I learn it, and I strongly recommend it to any ReSharper user. It contains a set of tip about navigating, code generation, refactoring, etc.

A good news, that this ReSharper training course available for free to any ReSharper user! If you want to get an access, contact sales@jetbrains.com with your license information.

More info about this offer – here and here


Wednesday, August 10, 2011 #

Recently I found interesting “feature” of fxc compiler (it’s a part of MS DirectX SDK). When you try to compile shaders, and path to source code contains non-Latin characters, you’ll get error like following:

Error 1 The command ""%DXSDK_DIR%Utilities\bin\x86\fxc.exe" /T vs_2_0 /O3 /Zpr /Fo "f:\импортер\SilverlightApplication1\Shaders\vertexshader.vs" "f:\импортер\SilverlightApplication1\Shaders\vertexshader.hlsl"
"%DXSDK_DIR%Utilities\bin\x86\fxc.exe" /T ps_2_0 /O3 /Zpr /Fo "f:\импортер\SilverlightApplication1\Shaders\pixelshader.ps" "f:\импортер\SilverlightApplication1\Shaders\pixelshader.hlsl"" exited with code 1.

As you can see, highlighted part of paths contains Cyrillic symbols. When I rename “импортер” to “Importer”, it compiled ok.

 

So, to avoid problems I recommend you do not use non-Latin characters in the path ;)


Tuesday, July 19, 2011 #

I purchased Office 365 subscription recently, and wanted to bind my own domain, because wanted to use e-mail address like alias@some_custom_domain.com

If you want to use custom domains, manual page suggest to change name server records for your domain to ns1.bdm.microsoftonline.com and ns2.bdm.microsoftonline.com. After doing this you can use aliases with your domain for Exchange mail and Lync.

If you don’t want to change by any reasons name servers for your domain, just go through steps:

1) open Domains page in your admin

2) click on your custom domain my_custom_domain.com

3) on the domain page click DNS Dispatcher

4) you can see “system’s” Office 365 MX, CNAME, TXT and SRV records (screenshot in my native Russian lang, but I think it’s not a problem to understand):

image

Add this records to your domain, and wait some time (about 10-30 min). After that you can use your custom domain to create users with full access to Office 365 services, and without using MS name servers.

Warning! This method is NOT suitable for any enterprise customers!! Because if “system” records are changed, your users can’t use one or any services (Exchange, Lync, etc) until you manually fix your domain records.

I tried to do it, and it’s working. I use Office 365 privately, so I wake up to a risk.

Good luck! ;)


Thursday, June 23, 2011 #

If you need to explore big amount of another’s C# code, C# outline add-in may be helpful. It allow you to collapse statements between { and }. Here is a sample screenshot:

image

This add-in available for Visual Studio 2010. Also, it’s not compatible with some other plugins like Presentation Zoom – outline nodes displaces, if both installed.


Monday, June 20, 2011 #

If you try to add large FBX 3D model to the XNA project, and build it, you can get an OutOfMemoryException build error like following:

Error    1    Building content threw OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.Collections.Generic.List`1.set_Capacity(Int32 value)
   at System.Collections.Generic.List`1.EnsureCapacity(Int32 min)
   at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
   at Microsoft.Xna.Framework.Content.Pipeline.Graphics.VertexChannel`1.InsertRange(Int32 index, Int32 count)
   at Microsoft.Xna.Framework.Content.Pipeline.Graphics.VertexContent.InsertRange(Int32 index, IEnumerable`1 positionIndexCollection)
   at Microsoft.Xna.Framework.Content.Pipeline.Graphics.MeshBuilder.AddTriangleVertex(Int32 indexIntoVertexCollection)
   at Microsoft.Xna.Framework.Content.Pipeline.MeshConverter.FillNodeWithInfoFromMesh(KFbxNode* fbxNode, String name, KFbxGeometryConverter* geometryConverter)
   at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.ProcessInformationInNode(KFbxNode* fbxNode, String name, Boolean* partOfMainSkeleton, Boolean* warnIfBoneButNotChild)
   at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.ProcessNode(ValueType parentAbsoluteTransform, NodeContent potentialParent, KFbxNode* fbxNode, Boolean partOfMainSkeleton, Boolean warnIfBoneButNotChild)
   at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.ProcessNode(ValueType parentAbsoluteTransform, NodeContent potentialParent, KFbxNode* fbxNode, Boolean partOfMainSkeleton, Boolean warnIfBoneButNotChild)
   at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.Import(String filename, ContentImporterContext context)
   at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter`1.Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import(String filename, ContentImporterContext context)
   //additional calls here …

 

My desktop PC have 8Gb RAM, and Visual Studio’s process devenv.exe use under 2Gb of it while build process (about 3.5-4Gb of RAM is always free). It’s obvious, that VS can’t address more than 2Gb of RAM, and when that limit is over, build process is fail.

OS on my PC is Win x64,  so I “charge” devenv.exe by using editbin.exe utility – in the VS Command prompt I run following:

editbin "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" /LARGEADDRESSAWARE

This command edits the image to indicate that the application can handle addresses larger than 2 gigabytes.

After that FBX file successfully built! Of course, you must put proper path to devenv.exe, depend on your installation path. If you are on Win x86, you need to do additional action – more info here.

 

P.S.: although now you can build a bigger files, than usual, keep in mind, that XNA have some restrictions on vertex buffer size etc., depend on your current XNA project profile (Reach or HiDef). And if your model’s vertexbuffer size more than 64Mb (with Reach profile), that model can’t be built and raise an error.


Sunday, June 19, 2011 #

Recently I found a problem with importing 3D models from FBX files: it sometimes imported partly. That is when you draw a 3D model, loaded from FBX file, processed by content pipeline, you got only part of meshes. “Sometimes” means that you got this error only for some files. Results of my research below.

For example, I have 10Mb binary FBX file with a model, looks like:

And when I load it, result Model instance contains only part of meshes and looks like:

Because models from other files imported normally, I think that it’s a “bad format” file.

When you add FBX file to your XNA Content project and build it, imported file processing by XNA Fbx Importer & Processor. On MSDN I found that FbxImporter designed to work with 2006.11 version of FBX format. My file is FBX 2012 format.

Ok, I need to convert it to 2006 format. It can be done by using Autodesk FBX Converter 2012.1. I tried to convert it to other versions of FBX formats, but without success.

And I also tried to import my FBX file to 3D MAX, and it imported correctly. Then I export model using 3D MAX, and it generate me other FBX, which I add to my XNA project. After that I got full model, that rendered well!

So, internal data structure of FBX file is more important for right XNA import, than it version!

Unfortunately, Autodesk FBX is not an open file format. If you want to work with FBX, you should use Autodesk FBX SDK. This way you can manually read content of FBX file, and use it everyway.

Then I tried to convert my source FBX file to DAE Collada, and result DAE file back to FBX, using FBX Converter (FBX –> DAE –> FBX). The result FBX file can be imported normally.

 

Conclusion:

  1. XNA FbxImporter correct work doesn't depend on version (2006, 2011, etc) and form (binary, ascii) of FBX file. Internal FBX data structure much more important.
  2. To make FBX "readable" for XNA Importer you can use double conversion like FBX -> Collada -> FBX
  3. You also can use FBX SDK to manually load data from FBX

P.S. Autodesk FBX Converter 2012 is more, than simple converter. It provide you tools like:

  • FBX Explorer, which show you structure of FBX file;
  • FBX Viewer, which render content of FBX and provide basic intercation like model move and zoom;
  • FBX Take Manager, which allow to work with embedded animations

Friday, May 13, 2011 #

Visual Studio 2010 is not support built-in syntax highlight for HLSL, and I found great soultion – NShader – HLSL\ GLSL \ CG - Shader Syntax Highlighter add-in for Visual Studio. And now editor window with loaded *.fx file looks like following:

image

NShader support VS 2008 and 2010, and it’s free.

Another way to get syntax highlight is to set VS for opening *.fx in Notepad++ (with one of HLSL language definitions, it hasn’t built-in support).

I like to stay inside Visual Studio, so I prefer NShader :)


Thursday, April 15, 2010 #

RTM version of .NET 4 and Visual Studio 2010 is available, and now we can do some test with it.

Parallel Extensions is one of the most valuable part of .NET 4.0. It’s a set of good tools for easily consuming multicore hardware power. And it also contains some “upgraded” sync primitives – Slim-version.

For example, it include updated variant of widely known ManualResetEvent. For people, who don’t know about it: you can sync concurrency execution of some pieces of code with this sync primitive. Instance of ManualResetEvent can be in 2 states: signaled and non-signaled. Transition between it possible by Set() and Reset() methods call. Some shortly explanation:

Thread 1

Thread 2

Time

mre.Reset();
mre.WaitOne();
//code execution 0
//wating //code execution 1
//wating //code execution 2
//wating //code execution 3
//wating mre.Set(); 4
//code execution //… 5

Upgraded version of this primitive is ManualResetEventSlim. The idea in decreasing performance cost in case, when only 1 thread use it. Main concept in the “hybrid sync schema”, which can be done as following:

 

internal sealed class SimpleHybridLock : IDisposable
{
    private Int32 m_waiters = 0;
    private AutoResetEvent m_waiterLock = new AutoResetEvent(false);
 
    public void Enter()
    {
        if (Interlocked.Increment(ref m_waiters) == 1)
            return;
        m_waiterLock.WaitOne();
    }
 
    public void Leave()
    {
        if (Interlocked.Decrement(ref m_waiters) == 0)
            return;
        m_waiterLock.Set();
    }
 
    public void Dispose()
    {
        m_waiterLock.Dispose();
    }
}

It’s a sample from Jeffry Richter’s book “CLR via C#”, 3rd edition. Primitive SimpleHybridLock have two public methods: Enter() and Leave(). You can put your concurrency-critical code between calls of these methods, and it would executed in only one thread at the moment. Code is really simple: first thread, called Enter(), increase counter. Second thread also increase counter, and suspend while m_waiterLock is not signaled. So, if we don’t have concurrent access to our lock, “heavy” methods WaitOne() and Set() will not called. It’s can give some performance bonus.

ManualResetEvent use the similar idea. Of course, it have more “smart” technics inside, like a checking of recursive calls, and so on. I want to know a real difference between classic ManualResetEvent realization, and new –Slim. I wrote a simple “benchmark”:

class Program
{
    static void Main(string[] args)
    {
        ManualResetEventSlim mres = new ManualResetEventSlim(false);
        ManualResetEventSlim mres2 = new ManualResetEventSlim(false);
 
        ManualResetEvent mre = new ManualResetEvent(false);
 
        long total = 0;
        int COUNT = 50;
 
        for (int i = 0; i < COUNT; i++)
        {
            mres2.Reset();
            Stopwatch sw = Stopwatch.StartNew();
 
            ThreadPool.QueueUserWorkItem((obj) =>
            {
                //Method(mres, true);
                Method2(mre, true);
                mres2.Set();
            });
            //Method(mres, false);
            Method2(mre, false);
 
            mres2.Wait();
            sw.Stop();
 
            Console.WriteLine("Pass {0}: {1} ms", i, sw.ElapsedMilliseconds);
            total += sw.ElapsedMilliseconds;
        }
 
        Console.WriteLine();
        Console.WriteLine("===============================");
        Console.WriteLine("Done in average=" + total / (double)COUNT);
        Console.ReadLine();
    }
 
    private static void Method(ManualResetEventSlim mre, bool value)
    {
        for (int i = 0; i < 9000000; i++)
        {
            if (value)
            {
                mre.Set();
            }
            else
            {
                mre.Reset();
            }
        }
    }
 
    private static void Method2(ManualResetEvent mre, bool value)
    {
        for (int i = 0; i < 9000000; i++)
        {
            if (value)
            {
                mre.Set();
            }
            else
            {
                mre.Reset();
            }
        }
    }
}

I use 2 concurrent thread (the main thread and one from thread pool) for setting and resetting ManualResetEvents, and try to run test COUNT times, and calculate average execution time. Here is the results (I get it on my dual core notebook with T7250 CPU and Windows 7 x64):

ManualResetEvent

ManualResetEventSlim

image9 image4

Difference is obvious and serious – in 10 times!

So, I think preferable way is using ManualResetEventSlim, because not always on calling Set() and Reset() will be called “heavy” methods for working with Windows kernel-mode objects. It’s a small and nice improvement! ;)


Monday, November 23, 2009 #

Today I saw interesting behavior in VS2008: when you try to edit any View in the ASP.NET MVC project, main window of VS is not responding. Effect is like a some “invisible” modal dialog window is shown, and you can’t close it by Space or Enter. When you try to click in any part of VS’s window, you get an error beep.

I tried to unload all of add-ins, uninstall Resharper, reset VS settings – it’s useless. Solution is here (big thank you, guys :)): uninstall “Microsoft Visual Studio Web Authoring Component” through “Programs and Features”, and install it again from the “\WCU\WebDesignerCore\WebDesignerCore.EXE” folder inside the VS2008 installation media.

After that VS is working normally!