Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, January 29, 2014

You might have a code that needs to download data from internet or access to a file on your local drive.. These kind of processes extends the response time of your software and you may want to take caution for that. Asynchronous Programming is the methodology to set the run time more responsive.

An example code is shown below (source: http://msdn.microsoft.com/en-us/library/system.io.stream(v=vs.110).aspx) Here the method is defined as async because loading files on local drive may take time.

private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string StartDirectory = @"c:\Users\exampleuser\start";
            string EndDirectory = @"c:\Users\exampleuser\end";

            foreach (string filename in Directory.EnumerateFiles(StartDirectory))
            {
                using (FileStream SourceStream = File.Open(filename, FileMode.Open))
                {
                    using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
                    {
                        await SourceStream.CopyToAsync(DestinationStream);
                    }
                }
            }
        }


Good resources on MSDN:

Asynchronous Programming with Async and Await (C# and Visual Basic)
http://msdn.microsoft.com/en-us/library/hh191443.aspx

Calling Synchronous Methods Asynchronously
http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.110).aspx

async (C# Reference)
http://msdn.microsoft.com/en-us/library/hh156513.aspx





Posted on 8:02 PM by Erdem

No comments

Tuesday, January 28, 2014

One can learn a lot from looking other peoples code. Especially if the code is well crafted. I am not sure how to find well crafted code but here I will list sources for c# codes that I can find:

Posted on 8:38 PM by Erdem

No comments

Saturday, January 25, 2014

In this example, we are moving one step further with data binding to a control element and we are updating our binding element with implementing INotifyPropertyChanged

The first task is to figure out how to group radio buttons. For example, you might have 2 group of options to select for a patient recording program. You might want to record the gender and age. If you want to do it with radio buttons, you’d have something like in the image



Here, gender and age range options are grouped differently so we can have two selected options at once. (If they were all grouped into one group, you’d only be able to select one option). This can be done in XAML, using the following:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <RadioButton GroupName="ButtonGroup1" Content="12 or younger" HorizontalAlignment="Left" Margin="36,61,0,0" VerticalAlignment="Top"/>
            <RadioButton GroupName="ButtonGroup1" Content="Between 12 and 18" HorizontalAlignment="Left" Margin="36,136,0,0" VerticalAlignment="Top"/>
            <RadioButton GroupName="ButtonGroup1" Content="18 or older" HorizontalAlignment="Left" Margin="36,211,0,0" VerticalAlignment="Top"/>

            <RadioButton GroupName="ButtonGroup2" Content="Female" HorizontalAlignment="Left" Margin="29,338,0,0" VerticalAlignment="Top"/>
            <RadioButton GroupName="ButtonGroup2" Content="Male" HorizontalAlignment="Left" Margin="29,388,0,0" VerticalAlignment="Top"/>
            <TextBlock HorizontalAlignment="Left" Margin="50,29,0,0" TextWrapping="Wrap" Text="Select Age Range" VerticalAlignment="Top" Height="32" Width="155"/>
            <TextBlock HorizontalAlignment="Left" Margin="50,306,0,0" TextWrapping="Wrap" Text="Select Gender" VerticalAlignment="Top" Height="32" Width="155"/>

        </Grid>



Now that we figured how to add multiple groups of radio buttons, let's go back to data binding. Now, I want to add another text that is controlled by the radio buttons. This text should have the information related to patient’s gender. In addition, it should update every time I select the corresponding radio button. First, I add this text in XAML as:


<TextBlock x:Name="GenderText" HorizontalAlignment="Left" Margin="36,491,0,0" TextWrapping="Wrap" Text="{Binding genderText, Mode=TwoWay}" VerticalAlignment="Top" Height="32" Width="352"/>

 In order to update this text with changes in radio buttons, the program should be able to tell if the status of the radio buttons are updated as well. For this, I need “Two Way Binding” so I have to change my radio buttons code in XAML file as:

            <RadioButton GroupName="ButtonGroup2" Content="Female" HorizontalAlignment="Left" Margin="29,338,0,0" VerticalAlignment="Top" IsChecked="{Binding patientFemale, Mode=TwoWay}"/>
            <RadioButton GroupName="ButtonGroup2" Content="Male" HorizontalAlignment="Left" Margin="29,388,0,0" VerticalAlignment="Top" IsChecked="{Binding patientMale, Mode=TwoWay}"/>


Now, my work with XAML is done and I need to update my MaingPage.xaml.cs In short, here’s a list of what I need to do in my .cs file to implement the code:
1. I need to inherit from INotifyPropertyChanged so when a property changes, I can detect it and do as I wish
2. I need to add string and Boolean properties to control the flow of the program and change the variables as I wish
Here’s how my .cs file looks like:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RadioButtonsBinding.Resources;


namespace RadioButtonsBinding
{
    public class Patient : INotifyPropertyChanged
    {
        public bool _patientMale;
        public bool patientMale
        {
            get {return _patientMale;}
            set { _patientMale = value; Notify("patientMale"); Notify("genderText"); }
        }

        public bool _patientFemale;
        public bool patientFemale
        {
            get { return _patientFemale; }
            set { _patientFemale = value; Notify("patientFemale"); Notify("genderText"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void Notify(string propName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));

        }

        public string _genderText;
        public string genderText
        {
            get
            {
                string common_string = "The gender of the patient is: ";
                if (_patientFemale)
                { return common_string+"Female"; }
                else { return common_string + "Male"; }
            }

        }
       
    }

    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        Patient newPatient;

        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            newPatient = new Patient();
            ContentPanel.DataContext = newPatient;
        }



    }
}


Now the program works as I want and here are the screen outputs:





The text dynamically changes every time I select a different gender with the radio button!


Posted on 3:41 PM by Erdem

No comments

Sunday, January 12, 2014

Zaman zaman variable lerin type ini degistirmek gerekebilir. Mesela double alan bir method var, ve buna int32 pass etmek istiyoruz. Boyle durumlarda variable'in type ini degistirmeye casting denir.

Eger int long'a veya double'a cevireleekse, burada veri kaybetme riski olmadigindan, implicit bir sekilde yani c# compiler tarafindan bu is halledilir.

Eger double int'e cevirelecekse burada veri kaybetme riski oldugundan, explicit bir sekilde yani user tarafindan variable tipi degistirmek gerekir. Buna da casting denir ve casting operatoru kullanmak icap eder.

http://msdn.microsoft.com/en-us/library/ms173105.aspx

Posted on 5:05 PM by Erdem

No comments

Generics bir class ve method tipi. Bu tipin ne avantaji var, islevi nedir.. Bunlari anlamak epeyi vakit alabilir.

Basit bir cerceve, application uzerinden ornek verirsek, Generics kullanmayarak bir liste olusturalim:

System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
list.Add(3);
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining in Redmond.");

Burada "list" objesi, hem String hem int elemanlar icermekte. Bunu saglayabilmesi icin bir upcasting olmasi lazim cunku hem int hem string ayni kefeye koyabilmek icin bunlari ayni cinse dondurmesi lazim. Burada int ve string object sinifina upcast edilliyor. Burada bir sorun yok ama kullanici int ve string den haberdar olmayarak, icinden cikilmayacak bir hata yapabilir. Bunu engellemek icin ihtiyacimiz olan, definition esnasinda direk tek bir type a cast edilmesi. Burda da Generics class devreye su sekilde giriyor:
// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();
// No boxing, no casting:
list1.Add(3);
Bu listenin elemanlari integer olmak zorunda dolasiyla casting kaynakli bir hata cikmasi soz konusu degil. Iste Generics basitce bu ise yariyor..


Posted on 4:59 PM by Erdem

No comments

Sunday, January 05, 2014

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

See the code below with several boxing and unboxing examples

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BoxingUnboxing
{
    class Program
    {
        static void Main(string[] args)
        {
            // String.Concat example. 
            // String.Concat has many versions. Rest the mouse pointer on  
            // Concat in the following statement to verify that the version 
            // that is used here takes three object arguments. Both 42 and 
            // true must be boxed.
            Console.WriteLine(String.Concat("Answer ", 42, " ", true));
            // burada 42 ve true string seklinde box laniyor


            // List example. 
            // Create a list of objects to hold a heterogeneous collection  
            // of elements.
            List<object> mixedList = new List<object>();

            // Add a string element to the list. 
            mixedList.Add("First Group:");

            // Add some integers to the list.  
            for (int j = 1; j < 5; j++)
            {
                // Rest the mouse pointer over j to verify that you are adding 
                // an int to a list of objects. Each element j is boxed when  
                // you add j to mixedList.
                mixedList.Add(j);
            }

            // Add another string and more integers.
            mixedList.Add("Second Group:");
            for (int j = 5; j < 10; j++)
            {
                mixedList.Add(j);
            }

            // Display the elements in the list. Declare the loop variable by  
            // using var, so that the compiler assigns its type. 
            foreach (var item in mixedList)
            {
                // Rest the mouse pointer over item to verify that the elements 
                // of mixedList are objects.
                //Console.WriteLine(item);
                Console.Write(item); Console.Write(" "); Console.WriteLine(item.GetType());
            }

            // The following loop sums the squares of the first group of boxed 
            // integers in mixedList. The list elements are objects, and cannot 
            // be multiplied or added to the sum until they are unboxed. The 
            // unboxing must be done explicitly. 
            var sum = 0;
            for (var j = 1; j < 5; j++)
            {
                // The following statement causes a compiler error: Operator  
                // '*' cannot be applied to operands of type 'object' and 
                // 'object'.  
                //sum += mixedList[j] * mixedList[j]); 

                // After the list elements are unboxed, the computation does  
                // not cause a compiler error.
                sum += (int)mixedList[j] * (int)mixedList[j];
                // burada da unboxing ornegi var
                // mixedList denen icinde boxed variable lerin oldugu liste burada her biri unbox ediliyor 
                // yeniden gosteriliyor
            }

            Console.ReadKey();
        }
    }

}

Posted on 10:16 PM by Erdem

No comments