Tuesday, January 6, 2015

Coding Experiences Part 3

Points to be covered:


  • 1. Create a user control to simplify WPF forms.(covered in previous post)
  • 2. Use Strategy pattern in a complex decision making scenario.
  • 3. Converters (this post) (covered in previous post)
  • 4. Create a template to make form creations faster (this post)
  • 5. Create a common print template to print all forms in WPF
Create a Master Page like template for faster form creations in WPF

FormTemplate here is a user control just like a master page, with dependency properties, placeholders for consumer views and common controls

Create a FormTemplate user control class like this:
InputControlsPlaceHolder is an example placeholder where the consumer will have to provide controls.
FormTitle is a property bound to a label in the usercontrol xaml, which consumers can set it.

public class EntryFormTemplate : UserControl  
 {  
      public EntryFormTemplate()  
      {  
           Initialize();  
      }  
      private void Initialize()  
      {  
           ResourceDictionary resources = new ResourceDictionary();  
        resources.Source = new Uri("Resources/FormTemplate.xaml", UriKind.Relative);  
           this.Resources = resources;  
      }  
      public object InputControlsPlaceHolder  
      {  
           get { return (object)GetValue(InputControlsPlaceHolderProperty); }  
           set { SetValue(InputControlsPlaceHolderProperty, value); }  
      }  
      // Using a DependencyProperty as the backing store for InputControlsPlaceHolder. This enables animation, styling, binding, etc...  
      public static readonly DependencyProperty InputControlsPlaceHolderProperty =  
           DependencyProperty.Register("InputControlsPlaceHolder", typeof(object), typeof(EntryFormTemplate), new UIPropertyMetadata(""));  
      public string FormTitle  
      {  
           get { return (string)GetValue(FormTitleProperty); }  
           set { SetValue(FormTitleProperty, value); }  
      }  
      // Using a DependencyProperty as the backing store for FormTitle. This enables animation, styling, binding, etc...  
      public static readonly DependencyProperty FormTitleProperty =  
           DependencyProperty.Register("FormTitle", typeof(string), typeof(EntryFormTemplate), new UIPropertyMetadata("Enter some title here."));  
 }  

Now you need to add this XAML file as a resource (explaination given at the end of this post):

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  
  <!--All your common styles should be placed here-->  
  <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextBoxStyle}">  
   <Style.Setters>  
    <Setter Property="MinWidth" Value="100"></Setter>  
    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(uc:DataFormItem.LabelText), diag:PresentationTraceSources.TraceLevel=High}"/>  
   </Style.Setters>  
  </Style>  
  <!--Converters-->  
  <conv:RadioConverter x:Key="enumConverter" />  
  <Style TargetType="{x:Type uc:FormTemplate}">  
   <Setter Property="Template">  
    <Setter.Value>  
     <ControlTemplate TargetType="{x:Type uc:FormTemplate}">  
      <Grid>  
       <StackPanel>  
        <Label Style="{StaticResource TitleLabelStyle}" Content="{Binding FormTitle, FallbackValue=Title, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type uc:FormTemplate}}}"/>  
        <ScrollViewer>  
         <ContentControl Height="auto" Content="{Binding InputControlsPlaceHolder, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type uc:FormTemplate}}}"/>  
         <!--Also include all common controls here with their bindings-->  
        </ScrollViewer>  
       </StackPanel>  
      </Grid>  
     </ControlTemplate>  
    </Setter.Value>  
   </Setter>  
  </Style>  
 </ResourceDictionary> 

Why was this done 

Why did we put the style in resource file and not in a user control XAML?

You cannot use named controls inside a user control which will be consumed by other views (this was the issue faced) The workaround was to create a user control class and give it a look by loading the style from the resource dictionary. Define your placeholder dependency properties here.

  <ContentControl Height="auto" Content="{Binding InputControlsPlaceHolder, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type uc:FormTemplate}}}"/>  Why is this done?

Relative source is important here. We will provide the controls for input placeholder in the consumer view, but we'll also have to take care that the properties of those controls will have the consumer VM as its data source.

Coding Experiences Part 2

Points to be covered:


  • 1. Create a user control to simplify WPF forms.
  • 2. Use Strategy pattern in a complex decision making scenario.
  • 3. Converters (this post)
  • 4. Create a template to make form creations faster
  • 5. Create a common print template to print all forms in WPF



Use datatemplates to switch views based on conditions

In your view place this in Resources tag


 <ControlTemplate x:Key="XYZ">  
 <local:XYZDetailsView DataContext="{Binding SelectedViewItem}"/>  
 </ControlTemplate>  

Then put a datatrigger in a Control style. When the bound property from the view model matches with the value, the static resource defined in your resources will define your control's template.


 <Grid>  
 <Control>  
  <Control.Style>  
   <Style>  
    <Style.Triggers>  
      <DataTrigger Binding="{Binding Path=SelectedViewItem.Type}" Value="XYZ">  
       <Setter Property="Control.Template" Value="{StaticResource XYZ}" />  
      </DataTrigger>  
    </Style.Triggers>  
   </Style>  
  </Control.Style>  
 </Control>  
 </Grid>  

Multi Datatriggers OR conditon example

Following example demonstrates an OR condition used in a multi data trigger

<TextBlock>
   <TextBlock.Style>  
      <Style TargetType="TextBlock" BasedOn="{StaticResource dd}">  
        <Setter Property="Text" Value="" />  
        <Style.Triggers>  
           <MultiDataTrigger>  
             <MultiDataTrigger.Conditions>  
                <Condition Binding="{Binding EmpInformation.EmpType}" Value="PE" />  
             </MultiDataTrigger.Conditions>  
             <Setter Property="Text" Value="Permenant Employee" />  
           </MultiDataTrigger>  
           <MultiDataTrigger>  
             <MultiDataTrigger.Conditions>  
                <Condition Binding="{Binding EmpInformation.EmpType}" Value="Permenant Employee" />  
             </MultiDataTrigger.Conditions>  
             <Setter Property="Text" Value="Permenant Employee" />  
           </MultiDataTrigger>  
        </Style.Triggers>  
      </Style>  
   </TextBlock.Style>  
 </TextBlock>  

Monday, January 5, 2015

Some experiences and ideas in coding Part 1

Points to be covered:


  • 1. Create a user control to simplify WPF forms. (this post)
  • 2. Use Strategy pattern in a complex decision making scenario.
  • 3. Converters
  • 4. Create a template to make form creations faster
  • 5. Create a common print template to print all forms in WPF



Create a user control to simplify WPF forms.

First define a style in your resource file:


 <!---MyDataForm Related Styles-->  
   <Style TargetType="{x:Type uc:MyDataForm}">  
     <Setter Property="ItemsPanel">  
       <Setter.Value>  
         <ItemsPanelTemplate>  
           <StackPanel Orientation="{Binding Orientation, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type uc:MyDataForm}}}"/>  
         </ItemsPanelTemplate>  
       </Setter.Value>  
     </Setter>  
     <Setter Property="Template">  
       <Setter.Value>  
         <ControlTemplate TargetType="{x:Type uc:MyDataForm}">  
           <Border Background="{TemplateBinding Background}"  
               BorderBrush="{TemplateBinding BorderBrush}"  
               BorderThickness="{TemplateBinding BorderThickness}">  
             <ItemsPresenter />  
           </Border>  
         </ControlTemplate>  
       </Setter.Value>  
     </Setter>  
   </Style>  
   <ControlTemplate x:Key="ConfirmationTemplate" TargetType="{x:Type uc:MyDataFormItem}">  
     <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Margin}">  
       <DockPanel LastChildFill="False">  
         <TextBlock Style="{DynamicResource TextGray13BoldLbl}" DockPanel.Dock="Top" Margin="10,1,0,0" Text="{Binding Path=(uc:MyDataFormItem.LabelText)}" />  
         <ContentPresenter Margin="10,0,0,0" />  
       </DockPanel>  
     </Border>  
   </ControlTemplate>  
   <ControlTemplate x:Key="EntryFormTemplate" TargetType="{x:Type uc:MyDataFormItem}">  
     <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Margin}">  
       <DockPanel LastChildFill="False">  
         <Label Style="{StaticResource NewDesignFormInputLabelStyle}" DockPanel.Dock="Bottom" Margin="5,1,0,0"   
                   Content="{Binding Path=(uc:MyDataFormItem.LabelText), Converter={StaticResource UpperCaseConv}}" />  
         <ContentPresenter Margin="2,0,0,0" />  
       </DockPanel>  
     </Border>  
   </ControlTemplate>  
   <Style TargetType="{x:Type uc:MyDataFormItem}">  
     <Setter Property="Template" Value="{StaticResource EntryFormTemplate}"/>  
     <Style.Triggers>  
       <DataTrigger Binding="{Binding Path=(uc:MyDataFormItem.IsConfirmation)}" Value="True">  
         <Setter Property="Template" Value="{StaticResource ConfirmationTemplate}"/>  
       </DataTrigger>  
       <DataTrigger Binding="{Binding Path=Visibility}" Value="Collapsed">  
         <Setter Property="Template">  
           <Setter.Value>  
             <ControlTemplate TargetType="{x:Type uc:MyDataFormItem}">  
               <Border Visibility="Collapsed"/>  
             </ControlTemplate>  
           </Setter.Value>  
         </Setter>  
       </DataTrigger>  
     </Style.Triggers>  
   </Style>  

Then create a class MyDataForm which is a user control:


  public class MyDataForm : ItemsControl  
   {  
     static MyDataForm()  
     {  
       DefaultStyleKeyProperty.OverrideMetadata(typeof(MyDataForm), new FrameworkPropertyMetadata(typeof(MyDataForm)));  
       IsTabStopProperty.OverrideMetadata(typeof(MyDataForm), new FrameworkPropertyMetadata(false));  
     }  
     public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(MyDataForm), new FrameworkPropertyMetadata(Orientation.Vertical));  
     public Orientation Orientation  
     {  
       get { return (Orientation)GetValue(OrientationProperty); }  
       set  
       {  
         SetValue(OrientationProperty, value);  
       }  
     }  
     protected override bool IsItemItsOwnContainerOverride(object item)  
     {  
       return item is MyDataForm || item is MyDataFormItem;  
     }  
     protected override DependencyObject GetContainerForItemOverride()  
     {  
       return new MyDataFormItem();  
     }  
   }  



Then create a class MyDataFormItem which is a user control:


  public class MyDataFormItem : ContentControl  
  {  
     static MyDataFormItem()  
     {  
       DefaultStyleKeyProperty.OverrideMetadata(typeof(MyDataFormItem), new FrameworkPropertyMetadata(typeof(MyDataFormItem)));  
       IsTabStopProperty.OverrideMetadata(typeof(MyDataFormItem), new FrameworkPropertyMetadata(false));  
     }  
     public static readonly DependencyProperty LabelTextProperty = DependencyProperty.RegisterAttached("LabelText", typeof(string), typeof(MyDataFormItem));  
     public static string GetLabelText(DependencyObject obj)  
     {  
       return (string)obj.GetValue(LabelTextProperty);  
     }  
     public static void SetLabelText(DependencyObject obj, string value)  
     {  
       obj.SetValue(LabelTextProperty, value);  
     }  
     public static bool GetIsConfirmation(DependencyObject obj)  
     {  
       return (bool)obj.GetValue(IsConfirmationProperty);  
     }  
     public static void SetIsConfirmation(DependencyObject obj, bool value)  
     {  
       obj.SetValue(IsConfirmationProperty, value);  
     }  
     // Using a DependencyProperty as the backing store for IsConfirmation. This enables animation, styling, binding, etc...  
     public static readonly DependencyProperty IsConfirmationProperty =  
       DependencyProperty.RegisterAttached("IsConfirmation", typeof(bool), typeof(MyDataFormItem), new UIPropertyMetadata(false));  
 }  


Usage in XAML


 <TextBox uc:MyDataFormItem.LabelText="Contact name" x:Name="txtContactName" Text="{Binding ContactName}" TextWrapping="Wrap"></TextBox>  

Other points covered in other posts

Sunday, November 23, 2014

Config file editor

A project in works, this tool reads a config file and allows you to edit and save attributes (for now)

MrConfig_version_1

Version 2
* allows to overwrite file with changes
* allows to edit attributes and element values

What's Mr. Config?

For developers and administrators who are frustrated and clueless when they open a config file in notepad and then do a search and replace; Mr Config comes to the rescue!

Mr. Config visualizes any config file as a tree view. It allows you to edit element values and attributes right inside the tree view!

You can then save this file and as a sweet side effect, your config file is also rightly indented and formatted.

Mr. Config lets you search for the specific nodes using XPath search. You can expand or collapse all nodes within the view.

Download link (with Visual Studio solution) :
MrConfig_Version_2

Sunday, September 28, 2014

Dog Walker (short story)

Dog Walker


‘It’s just suicidal for your career. It’s stupid, it’s mindless, and it’s idiotic. You’re wrecking yourself! You’re acting like a total maniac. You’ll end up screwing your life.’

My friend (the boy) was getting an earful from my other friend. ‘Don’t worry…’ I paused, taking care not to let the sandwich fall off my mouth, ‘…all of what he said may happen except for what he said in the end’, I said coolly to the boy. ‘Thank you for your one line opinion in this two hour conversation. And thanks for making my half munched sandwich disappear too!’ the advisor friend lamented me. Well I had to admit, the guys at these coffee shop served the best corn sandwiches with mayonnaise graciously melted in between the layers. Besides, I wasn’t paying attention to their talk.

Apparently the boy, who was working in a reputed bank in the marketing division, had made up his mind to quit the job. You must be wondering why the advisor friend called this move as ‘suicidal, mindless, wrecking, maniacal decision’. Well, the boy wanted to advance his career of course; by applying to the post of a dog walker.

‘Well the money’s good, and I want to try something different too!’ explained the boy. Although there was no point for him to falsify the real reason before us; he kept on saying this as his reason to quit the desk job. Let me explain you the real motive in a few sentences. The boy’s office was in a plush business park cum residential complex. The advisor friend lived with the boy in a rented apartment outside the complex. The advisor friend’s distant cousin lived in one of the residential buildings. One fine evening, the two left the office and took the regular walk towards the bus stop outside the complex. On the way, they happened to see the advisor friend’s cousin, so they stopped by for a chat. The boy obviously had nothing to participate in this chat, but it here where he sees this girl…who is pretty, attractive, whatever you’d like to call. Now the boy gets the information from the advisor friend, who gets this information from his distant cousin that the pretty girl happens to stay in his building. And in a measure to get close to her, the boy gets this information from his advisor friend, who in turn gets this information from his distant cousin, who then gets this important piece of information from the security guard of his building, that a position for a dog caretaker has been just vacated and someone is urgently needed to fill in this post; for which our hero, the boy, is vying for. Whew! Now never ever ask me to explain anything in few sentences!

The girl. Light fawn in colour. Her hair was delicate, colour burgundy. She made herself quick pony, still hair strands or two fell and touched her forehead. Her shapely eyebrows looked like vertically mirrored tick marks; ones which your class teacher used to give on your test papers. Her eyelashes were similar in shape like the rooftops of temples in China. Her skin was flawless. Her lips were chiseled and it looked like she might have been born with a permanent apple shaded lip gloss applied. She wore a dark emerald top and her delicate arms looked prominent. She folded her slim, shapely legs, on top over the other. Suddenly she unfolded them and brought them close to each other. Probably some interesting joke or a message on WhatzApp made her do this.

Her mom was on her right. Her young brother looked shabby and was occupied with his PlayStation portable. And her dad’s pea sized mole, struck directly in between his chin was quite disturbing, as the boy was trying to pay attention to him; on his ongoing interview.

And so began the endeavor, the quest, to come closer to his love. During the interview she glanced at him once! He was happy at the progress. And he got the job too! The pay wasn’t bad either. He had to visit three times a day and had to take care of a friendly Labrador and an ugly looking Pug. He had to do all of the conditions and the duties that her dad yelled at him. That was easy!

The first morning, the dogs refused to eat, as they were not accustomed to the boy. The opportunist boy, got to speak with the girl on what can be done to convince the dogs, to which she plainly replied that she loves her dogs a lot, but doesn’t meddle herself in their caring. Other day, the boy got introduced to the girl’s shabby brother, when the boy had to wear shabby’s denim shorts. Well in an untoward incident, while bathing the dogs, the boy accidently touched those areas where angels fear to tread and got himself a scar on his face, and an attack on his left buttock, resulting in torn pants. ‘Keep them for yourself and don’t dare to return them’, the shabby brother said, resulting in additional humiliation and awkwardness the boy had to face when he had to go home wearing those tight denim shorts.

Things were getting a bit easier with the dogs as the days went by. The boy’s back problems aggravated as the Labrador weight pulled his spine with a force. The girl’s mother otherwise loathing him, this time showed her kindness by giving him an allowance, to go and visit a doctor, with the condition of not taking a leave.

And on that day, the girl finally spoke to him, herself.

‘I see your back pains have worsened,’ said the girl, not looking at the boy. She was multitasking; doing something on her iPhone. ‘Too bad for a guy with a desk job experience!’ she taunted. The boy sprang up. He had faked his resume (verbal) and had never mentioned a desk job or his previous work. ‘You may have deleted all your social networking profiles, but you forgot your LinkedInn profile!’ she said with a slight smile. The boy closed his eyes with despair, but kept cool. He jogged through the thoughts of how this gaffe might have happened; but the girl was way too fast for him.

‘Look,’ said the girl, this time looking at him directly. In this tension, the boy noticed the colour of her eyes. They were deep dark brown, like the chocolate fantasy they’d serve at the coffee shop. ‘I am aware of your intentions,’ she said, looking down, her lips pressed. ‘You seem to be a nice guy, but this is not going to go anywhere,’ she said, leaving the conversation dangling and left abruptly. The boy simply smiled. Then he took the dogs out for their evening walk, bearing the two pains he had; spinal and the heart break.

‘Come on laddie…want a kick on your butt? Out you go!’ said a stern, loud voice.

The boy came out, in the light. I was standing next to the advisor friend, as we looked at the boy. His face looked dry. He closed his eyes, took a deep breath and exhaled. ‘Feels great…,’ he said, looking at us, ‘Let’s go! Why are we standing here?’

We were in the coffee shop. The boy that day after the brief conversation with the girl had taken the dogs for their walk. An incident had let the leash get out of his hands, which triggered the dogs to run and get away, not to be found. The girl’s dad had got him jailed for 1 month and a certain amount of fine for the loss; one of terms of agreement he had stated when he accepted the job.

‘So, what’s next?’ I asked him, my subconscious chose asking the question over the temptation of the corn mayonnaise sandwich in front of me.

‘Down, but not out. I’ve just started!’ he smiled. There was a sparkle in his eyes and I had never seen such a wide smile on his face, until now.

Mangesh Nadkarni
28-09-2014



Sunday, August 24, 2014

(Short Story) The Girl who liked French Fries

The Girl who liked French Fries


By Mangesh Nadkarni (11/04/2010)

Sitting on seat number 36 while returning to Mumbai from one of my recent Pune trips, the bus halted at a food mall midway during the journey. I woke up from my partial doze. The headphones had gone misaligned, and my throat felt dry, which meant my mouth was open during my sleep. I cursed myself yet again for my embarrassment.

I didn’t get up although I felt the need of getting my face washed, to feel fresh. As a policy of my own I spend the first half sleeping and the next looking here and there. I avoid reading as I feel it is a primary catalyst for inducing sleep. Well the ‘real’ reason of not getting down the bus was this pretty girl who sat on the right corner of the two seats front of mine. Never mind I hadn’t drank much water and there was no real need to visit the loo, though sometimes we all do it for our ‘safety’. I sacrificed my ‘safety’ to have a look at her, when her boyfriend wasn’t around! “Mmmm..French Fries for me!” she wailed cutely at her boyfriend who proceeded to get down. I cried to myself why I wasn’t her McDonald.
She hadn’t streaked her straight hair, well that would look cute on her. Her ‘pinch able cheeks’ looked amazing on her not so chubby face. Mind you, the view was from her sideways. I never imagined how luscious one’s lips could look from that view. I cursed the caller who prompted her to pick up her mobile and talk, ruining my view. The call was short, presumably her boyfriend’s, asking “Do you want that extra cheese baby?” I never overheard that, but guessed it so, because of her obvious “no” to my ‘guessed’ extra cheese.

Tomorrow was Valentine’s Day and I so wanted her to be with me!! She looked outside the window and that wasn’t so good for my view. “Well let her look!” I said to myself in my mind. Then she picked up an Auto Car magazine and flipped few pages and threw it on the adjacent ‘boyfriend’s’ seat by force. It looked like she missed Femina or Cosmopolitan, oh sorry, Vanity Fair! Her bottle green top looked fabulous and I was lucky to admire her smooth hands. That was the closest my eyes could get thanks to the rift between two seats. My eyes were shamelessly (I thought about that afterwards!) fixed on her slim stable arm for a long time. Suddenly that fixation broke loose as her arm moved, as it grabbed a brown paper bag with McDonald’s logo. “Darn the delivery boy,” I said to myself.

The next thing I heard was a transition. Her cute voice had apparently gone for a vacation as she shouted, “You’re such a jerk!!” That was for her boyfriend. He had brought only one tiny sachet of ketchup. “You know I need more ketchup. Why do you always keep forgetting?” All other passengers had already occupied their seats and the bus left after the conductor’s checking.

And so the bus started on the conductor’s mark. After that it was all exercise for my neck and eyes. I thanked God for our fixed ears and wished for cat like ears. “Paani doge?” she asked her boyfriend. What followed after that question was lots of gunfire. He repented for having forgotten to buy the bottle. Twenty bucks could have suppressed her ire. Then after a brief silence she murmured, “You never take care of me…”, to which he replied, “I’m sorry Namrata…really I..” “Shut up!” she said in a stern voice, forgetting the fellow passengers around her. “Aah…Namrata” I said to myself looking at the expressway!
I was impressed by the guys coaxing and then began the dreaded public display of affection! They held each other’s hands, trying to find a perfect grip. I didn’t understand how I missed out the part where a fellow passenger uncle lent his water bottle to the guy to extinguish the fire. The chirping of the two sparrows was on and I could see her smile and laugh. “Why do you read such useless magazines?” she asked the guy, flinging the Autocar she picked up, at him.  “That’s because I love cars..” he replied back politely. “Typical of boys…all they like is unusual stuff, and forget about us, what we need” she said in a somewhat harsh tone, tauntingly referring the ‘untoward’ incident happened earlier. Mr. Boyfriend wore a dejected look on his face. “What’s the matter now? I’ve still allowed you to talk!” she pricked him. He kept quiet. “Brownie points for this guy for keeping his cool!” I said to myself!

We zipped past Panvel, Sion, and were now on the Western express highway. “Care to ask the conductor when is Andheri coming?” she irked the guy. Blinking his eyes forcibly, he went up to the conductor. “Few minutes…” he said to her, after coming back to his place. “How many minutes did he say?” asked Namrata. I won’t describe what followed next.

“So what are we doing tomorrow?” she asked him. He kept quiet and looked engrossed in some thought. After a brief moment of silence, she asked him gently, “Would you be my Valentine this year honey?”

“Nope”, we replied. The guy hadn’t uttered anything. Namrata and the guy sprung their necks, looking at me. In spontaneity, I had responded in a low tone, but I tried figuring it out who else shared my opinion. I found myself staring at a pretty girl at the window, sitting next to me!!

Friday, August 15, 2014

Slumber (a short story)


Slumber

‘You know something strange happened to me yesterday,’ he said to his friend. ‘What?’ his friend asked, keeping aside his phone, with which he was preoccupied with.

‘Well yesterday morning, I took my office bus as usual. It was running a little late, which is quite normal. The colleagues whom I see each day at the stop too boarded the bus along with me. The bus was quite packed, more than usual. I looked around for a seat, got one and sat.’

‘Was it a window seat?’ the friend asked.

‘No,’ he replied firmly. ‘I don’t like to sit beside the window. Dust, pollution, you know.’

Continuing his story he said, ‘so then I got settled, drank some water as per my habit. I saw the group of young boys and girls, frolicking and cracking jokes and patting each other candidly. They quite regularly board this bus. It is a very jovial group, but I don’t like the chaos they make.’

‘I hadn’t slept the night before and tiredness crept into my eyes. I don’t usually take a nap in the bus, but since the journey is about 2 hours, I thought it was a good idea to rest.’

‘The bus was pacing fast as there seemed less traffic than usual that day. I saw out of the window. Those underwear advertising hoardings that I see every day appeared. I find them awkward. The guy next to me was wearing dark glasses, which I found unusual as it was cloudy that day. He had placed his bag on his lap. On top of his bag he had placed his left palm, and had put his elbow next to it. His index finger pressed against his lips. It looked like he was in deep thought. But he also had his earphones on, so I think he might be engrossed in some audio book or some thought inducing music.’

‘My eyes began to heavily droop. Sleep was overtaking me; still my eyes were set outside the window, even as the bus sped fast, as if the driver was on some mission. I saw two cars coming out of a crematorium. Suddenly the thought of death and dead people struck me. I felt bad for those people in those cars. Then I thought about circle of life.’

‘My mind was going blank as overcoming sleep was almost impossible to me. The last thing I remember what I saw before my eyes shut down, was traffic signals, which surprisingly green each time; quite unusual for this time of the day. I could hear the laughing from the chaotic jovial group, faintly. It was airy. The thinker guy beside me was still deep in thought, looking outside. Then…I went dark. I felt completely comatose. I felt dog-tired. I felt as if I hadn’t slept for many days and I was covering up this huge sleep deficit. I was lost in sleep. But I was still feeling the wind gushing on my face. I did feel the bus was in motion, thanks to the potholes.’

‘I was in my siesta, but a strange feeling overcame me. Our bus has pretty good suspension, but as the bus sped more, the jerks became lesser. I suddenly didn’t feel a thing. Not even the blanket of gushing wind on my face. Feeling recharged, I opened my eyes, but the strong sunlight hurt my eyes and I closed them immediately. Then slowly I opened my eyes.’

‘I looked straight at the right seat ahead of me. It was empty. I remember, a girl from the chaotic jovial group occupying it. Hurriedly, I saw to my left. The thinker was nowhere to be found. I looked to my right. No one. I got up from my seat and to my amazement the bus was empty and still. My heart stared beating faster. Composing myself, quick thoughts came to me. It must have slept till the end and everybody must have got out of the bus and gone to office, but no one must have woken me up. I have seen that happen with some people in the bus, but why would anyone have not woke me up till now? Quickly I started getting down from the bus, with my back pack.’

‘What followed next was bizarre to me. The bus had stood still. There was no sign of the driver. Outside the entrance door of the bus I saw overgrown grass. I was looking at a land covered with thick grass and dense trees and leafy plants around me. I was in shock. Then I touched the bus, to get a grip of reality. I indeed feel the coldness of the metal. But still I saw the grassy land lay ahead of me. Ants and insects started creeping on my feet which was unprotected as I was wearing sandals. I ran towards the back of the bus and looked around. It looked as if I was alone with the bus in a jungle.’

‘I took out my cell phone which had no network coverage. I asked myself, what should I do now? Should I shout? Call out for help? What was happening to me? I got inside the bus again. It was still empty. I was puzzled and my mind was shattered. The only option was to keep walking and getting out of this place. But this thing was unexplainable. Why would I be stranded in a jungle with a bus. Where was everyone? Had there been an accident? These thoughts came to me as I took on a direction and kept walking.’

‘I kept walking on for some 15 minutes and my heart was pounding at a faster rate. Suddenly out of nowhere, I saw a short fence. It too was covered with grass as the path throughout. Then to add to the list of strange events happening to me that day, I saw people sneaking through that fence, which had an opening, deliberately made my some to break into. A bald guy with a back pack was making his move to sneak in. In a flash I caught him and asked where were all these people going? He coldly replied to me, the name of my office!’ I was aghast. My office! How could that be? In this jungle? I thought it was probably better not to question anyone now and I quickly sneaked in with others and followed them.’

‘The trail of about 3 minutes ended. I saw my office building; the exact same building which I go into every day. I turned opposite, to see the jungle from where I came from. I went to my desk in a state of shock. There were the regular people whom I work with on the floor.’


‘So, this is what happened to me yesterday. It’s completely unexplainable isn’t it?,’ he asked his friend. Strangely now, there was no one in front of him.

Mangesh Nadkarni, 15-08-14

Sunday, August 3, 2014

MultiDataTrigger : Handle OR condition


Building on my previous post on MultiDataTrigger, we saw that MultiDataTrigger generally works for AND conditions (all conditions should be true to fire the trigger to update the property)

What would you do to handle OR condition?

<Style x:Key="pricestyle" TargetType="TextBox">
            <Setter Property="Visibility" Value="Collapsed"/>
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding AllowCheck}" Value="True"/>
                    </MultiDataTrigger.Conditions>
                        <Setter Property="Visibility" Value="Visible"/>
                </MultiDataTrigger>
                <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding Action}" Value="SELL"/>
                    </MultiDataTrigger.Conditions>
                        <Setter Property="Visibility" Value="Visible"/>
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>

Effectively you would need to write 2 multi data triggers to get this working.

Side notes (not related to this post topic)
http://stackoverflow.com/questions/17598200/datatrigger-binding-in-wpf-style
http://stackoverflow.com/questions/15814639/consolidating-common-wpf-styles

Saturday, August 2, 2014

MultiDataTrigger in WPF: an example

Here is the XAML
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style x:Key="pricestyle" TargetType="TextBox">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding AllowCheck}" Value="True"/>
<Condition Binding="{Binding Action}" Value="SELL"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter Property="Visibility" Value="Visible"/>
</MultiDataTrigger.Setters>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel Margin="20" HorizontalAlignment="Left">
<Label Content="Action" Margin="0,3,0,0"></Label>
<ComboBox Width="100" ItemsSource="{Binding Actions}" SelectedItem="{Binding Action, UpdateSourceTrigger=PropertyChanged}"></ComboBox>
<Label Content="Price" Margin="0,3,0,0"></Label>
<TextBox Width="100" Margin="0,3,0,0" Style="{StaticResource ResourceKey=pricestyle}"></TextBox>
<CheckBox x:Name="dd" Content="Allow" IsChecked="{Binding AllowCheck, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></CheckBox>
</StackPanel>
</Grid>
</Window>

On acceptable values defined in the trigger (highlighted in blue colour), on selection of Allow checkbox and SELL from action combo box, the trigger gets fired and the price textbox gets visible.


One important thing to note here (which may get missed out). Note the text in red colour. It's important to set a default state of the property for which you want the trigger to be applied on (in our example, its Visibility property of the textbox)

Sunday, July 6, 2014


XAML to ViewModel creator.

This demo is in works. Currently it reads a XAML file (using XElement) and identifies Bindings and their controls.

Next i'll complete this by printing out a view model class with properties using the bindings that i've collected in a collection.

You may want to improve this; feel free!

Download Demo Code

Placeholder trial: Placeholder code
Update to placeholder: Handle events of a control within a datatemplate. Refer this link:
http://stackoverflow.com/questions/1800595/event-handler-in-datatemplate

Tuesday, July 1, 2014


WPF: Quick way to display columnar data for printing. The code below displays textblocks in 2 columns. You can bind this listview or place data in XAML as shown below.

<ListView SelectionChanged="ListView_SelectionChanged_1" x:Name="lview"> <ListViewItem></ListViewItem> <ListView.View> <GridView x:Name="gview"> <GridViewColumn Width="100"> <GridViewColumn.CellTemplate> <DataTemplate> <StackPanel> <TextBlock HorizontalAlignment="Stretch" Text="hello"/> <TextBlock HorizontalAlignment="Stretch" Text="hello"/> <TextBlock HorizontalAlignment="Stretch" Text="hello"/> <TextBlock HorizontalAlignment="Stretch" Text="hello"/> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <StackPanel> <TextBlock HorizontalAlignment="Stretch" Text="mangesh"/> <TextBlock HorizontalAlignment="Stretch" Text="mangesh"/> <TextBlock HorizontalAlignment="Stretch" Text="mangesh"/> <TextBlock HorizontalAlignment="Stretch" Text="mangesh"/> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView>


Things such as hiding column headers, setting column width if required need to be done.

2 column grid example

Sunday, May 18, 2014

User controls for clutter free forms in WPF

User controls for clutter free forms in WPF

https://sites.google.com/site/mvnworldinc/Home/UserControlTest.zip?attredirects=0&d=1

Exposing inner Control properties for binding in WPF

http://stackoverflow.com/questions/4169090/exposing-inner-control-properties-for-binding-in-wpf

http://stackoverflow.com/questions/18158500/usercontrol-dependency-property-design-time

http://tech.pro/tutorial/807/wpf-tutorial-how-to-use-a-datatemplateselector

http://stackoverflow.com/questions/3922908/changing-contenttemplate-based-on-listbox-selection

http://breakingdotnet.blogspot.in/2012/05/data-template-selector-in-xaml.html

http://jacobaloysious.wordpress.com/2013/08/19/mvvm-using-contenttemplateselector-in-tab-control-view/

http://www.experts-exchange.com/Programming/Languages/.NET/Q_28029825.html

http://zamjad.wordpress.com/2011/09/21/using-contenttemplateselector/

Demo of how user controls can have their own VM
https://sites.google.com/site/mvnworldinc/Home/UsercontrolVM_Demo.zip?attredirects=0&d=1

Tab Header with context menu button:

Sample

Sample 2

Tuesday, April 15, 2014

Wiring Views and ViewModels using DataTemplate in resource dictionary in Prism:


Replace square brackets with <> tags

1. In module Initialize() :

// Merge Resource Dictionaries
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("pack://application:,,,/Project.AssemblyName;component/MainResourceDictionary.xaml ");
Application.Current.Resources.MergedDictionaries.Add(dictionary);

2. Create a main resource dictionary:

[ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vw="clr-namespace:Project.AssemblyName"
    xmlns:v="clr-namespace:Project.AssemblyName;assembly=Project.Views"]
    [!-- Resource dictionary entries should be defined here. --]
    [DataTemplate DataType="{x:Type vw:VM_1}"]
        [v:View_1 /]
    [/DataTemplate]
    [DataTemplate DataType="{x:Type vw:VM_2}"]
        [v:View_2 /]
    [/DataTemplate]
[/ResourceDictionary]

3. In Views project, your user control:

[UserControl x:Class="Project.Views.View_1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:Resx="clr-namespace:Project.AssemblyName"
      ..

Question posted:

http://goo.gl/MI1YCz

Others:
http://wpfthemes.codeplex.com/discussions/43074
http://transitionals.codeplex.com/releases/view/15792
http://stackoverflow.com/questions/9796174/load-usercontrol-in-tabitem
https://compositewpf.codeplex.com/discussions/30673

Saturday, February 22, 2014

A tutorial application in WPF

When you're new to some project and new to its application, a tutorial could be of use to quickly understand the application, its purpose, what its components do and what is the intention of the application. While there is no substitute for personal training, a simple tutorial app could get you started quickly. Plus there is always an advantage to look back at it whenever you want without any time limitation.

Here is a simple idea and its simplest implementation in WPF. It's just a starter.

Download Demo

Update:
I thought it'd be easier, faster and better if this were implemented in html using jQuery. I got a chance to learn jQuery because of this and ended up making a demo page. Hope someone builds up on this.

Download Demo in JQuery

Update 28/03/14: Intro.js is an amazing jquery library. Thanks to the developers.

Demo with intro js

TL_App_Concept

Friday, January 1, 2010

Time: A tale of three moving needles.

Fast do I move?

Slow do I seem?

I start at dusk.

Or at the first sunbeam.

Foolish you humans,

Err and make mistakes,

Waste me or use me or foul mouth me,

Careless me, I move with my own pace.

Rewind me in your thoughts,

Feel pleasure but mostly pain,

Try to call me back,

Or drive me off in vain!

Thursday, December 31, 2009

Of Capacity and Quality..

MP3 players remain popular as new models roll out periodically. We not only care for the design aesthetics but also the capacity of the player to hold songs so that we may never require adding songs that have been left out apart from the latest ones. When I think of the ‘capacity’ as in 8GB, 16GB and 32GB, I compare it with the higher capacity hard drives which are in the market today. It took me back to the year 2000 (now I could say, “a decade ago”!), when I had this Seagate 20GB drive. It was massive in size compared to what we look at today (size zero?). And the capacity? Tiny!!


With a 500GB HDD being a regular drive on home computers, whenever I’ve visit my friends, what I see is the enormous collection of movies and TV episodes of many “popular” sitcoms. A 10 to 15 GB collection of songs is bare minimum. But how much one hear the erstwhile gazhals (erstwhile on the drive!)? how much do we watch the sitcoms apart from all episodes of FRIENDS? And the movie collection is nothing to be proud of as many of them are just archived because we couldn’t find anything better than that!


With my old 20GB HDD, I remember how choosy I was. I used to convert some MP3s, apart from my favorites at the cost of quality, to OGG!! Now wonder why I did that!! I really saved some MBs! I used to archive old files and compress them, not choosing the popular Winzip but going for WinAce (anyone uses it now? I don’t!). I never knew WinRAR then. Once I got a 50MB software from a friend compressed in UHARC format and was amazed when I unzipped it as it had the command line interface and the unpacked software was well over 200MB!! I immediately used it (for a while of course).


I was kept songs that I heard more than once not compromising my collection. Back then CDs were a little expensive. I archived movies on them which I liked and kept some on my drive. What I learnt from my 20GB HDD was discipline. Effective partitioning and quality of data was of importance, which I think sadly is missed these days. What we do is get anything and everything. I still don’t own a 500GB or a 1TB HDD, but I wonder how would I stick on my ‘principles’?!

Friday, April 10, 2009

A Good Friday




Well today happens to be Good Friday (the holiday day for some of us) and it was also our group mate Chinmay's marriage. Good Marriage!!

Manas and i reached first at 10, the venue being Shruti Mangal Karyalay. Vishal came in with his dad, in traditional avatar. Later he would be only accompanied by Ranjeet in traditional attire, as the rest of us were in formals. It was an injustice, but considering the heat, give us a clean chit!


Narendra made a short presence as he had to go to the office. Ajay followed suit. It was pleasant to see Prakash Ramchandran (it had been a while seeing him). Jeetu, Pushkar and Ankur Shah (combo offer of sorts) too were present.

Abhijeet Thakur was a delight, as we have been really good friends, and it had been a long time we hadn't met. He had come from Aurangabad specially to attend the wedding. Nice!

Then followed an adhoc but a pretty good program of going to "Mee Shivajiraje..", Manjrekar's latest marathi film, which has become a cult lately. I had planned uniting many of us at Ranjeet's place and watch "Bolt", which i had copied on my pen drive. But that didn't materialise. In due course we saw a Mazda RX8 in the parking of E-Square ;) WOW!



We enjoyed the movie and i am now home. Let's see what rest of the day follows. It was a pleasant day having met old friends and enjoying with them!

Thursday, February 26, 2009

Music Review: Rahul Sharma & Richard Clayderman - Confluence II

VERDICT: WOW!! Confluence is a fantastic and a mind blowing album.
Track listing:
1 Dance Of The Sufis
2 Pure Flame Of Love, A
3 Chase, The
4 Dance AveeTa Vie
5 Fragrant Night
6 Endless Love
7 Forbidden Dreams
8 Le Chant Des Algues
9 Chase Continues, The

Dance Of The Sufis
----------------------------------------
The first track starts with RC's prelude piano. RS then picks it up from him, and sets the stage. The beats get groovier, making the track dancable. You would want to do a tango on this one! The middle is a reminiscent of a track(Fragrant Night) which comes later.

A Pure Flame Of Love
-----------------------------------------
RS's santoor makes its grand entry, while RC's piano lights up the atmosphere in the background. True to its name, its a soft musical perfect for night ambience. RC creates magic with beautiful orchestration. What's more, RC plays the "anatara" of this masterpiece. RS doesn't let you forget his prelude. It’s a fantastic song and keeps the mood 'alive' and 'afresh'. The pace of the song is smooth and soft. Not too slow, not too fast. RS $ RC have their fair share in this track, with each one playing their piece. Certainly, one of my favourites!

Dance AveeTa Vie
-----------------------------------------------
The santoor and the piano in this track have been kept in shade. The track didn't make me say "wow". It would be okay to skip this track or have a listen to it once.

Fragrant Night
-----------------------------------------
How can the santoor and the piano be used in a hip hop track? Baffled? The answer is "fragrant night". I couldn't relate the music with the name, but its one of the most exciting tracks in the album and has become an instant favourite. RS $ RC have indeed succeeded in making music 'different' altogether apart from taking it to a different level. RC's piano is played in 2 modes, one is subtle and to match RS's firm santoor tune, he plays firm piano notes! WOW!

Endless Love
--------------------------------------------
This track instantly reminds you of the waltz. Its touching, and soothing. It’s an amazing track. RC $ RS have given their best in this track. You certainly cannot miss this one. It matches in tune with the name and symbolizes romance. A splendid example of how an instrumental piece makes you visualise it as a song; something which is not easy to do. The ends are foot tapping and the song is joyous.

Forbidden dreams
---------------------
Again a fast paced track. the prelude of the track is racing, it just gets better and better in the middle. The orchestration is amazing and sounds dramatic! True to its name; you cannot stop yourself from seeing forbidden dreams!

Le Chant Des Algues
--------------------------------
RS and RC do an Enigma. With the hustling background and lightly emphasised santoor with a tinge of the piano, the track is kept short and sweet.

Chase Continues, The
-------------------------------------
Taking queue from Time Traveller, a revisit to the "Chase" sounds exciting. With more instruments added, like the tabla, and remixing, the track is more of an addition. Something, which wasn't required, but too good to be ignored.