Ibraheem Osama Mohamed (ابراهيم اسامه محمد)

Welcome to my blog :)

Archive for the ‘C#’ Category

Changing AppBarButton Icon on Run time in Windows 8 (Windows 8.1)

leave a comment »

Today I was testing the AppBarButton in Windows 8.1 and I thought of what if I want to change the Icon of the AppBarButton ex : from zoom out to zoom in??

<AppBarButton Click=”Zoom_Click_1″ Label=”Zoom Out” Icon=”ZoomOut” Name=”ZoomOutButton”/>

4

Just change the Icon property on the button click event but take care of something Icon Property takes IconElement and there are 3 class that inherits from it

FontIcon
PathIcon
SymbolIcon

So you can use any of those class to change the AppBarButton Icon in this sample I used the SymbolIcon

bool IsZoomIn = false;

        privatevoid Zoom_Click_1(object sender, RoutedEventArgs e)

        {

            if (!IsZoomIn)

            {

                ZoomOutButton.Label = “Zoom In”;

                ZoomOutButton.Icon = newSymbolIcon(Symbol.ZoomIn);

                IsZoomIn = true;

            }

            else

            {

                ZoomOutButton.Label = “Zoom Out”;

                ZoomOutButton.Icon = newSymbolIcon(Symbol.ZoomOut);

                IsZoomIn = false;

            }

        }

5

So simple 🙂

2056910448_thanks_xlarge

Ibraheem Osama Mohamed
[MVP]
@IbraheemOM

Advertisements

Written by Ibraheem Osama Mohamed

November 9, 2013 at 1:10 pm

Posted in C#, Windows 8, Windows 8.1, xaml

Windows 8 Secondary Tiles with Live Tiles C# (Arabic)

leave a comment »

هل تحب مواقع الاخبار ؟ هل يوجد قسم محدد الذى تحب دائما لقراءته !! فى تطبيقات الاخبار كى تصل الى القسم المراد تقوم بعددة خطوات للوصول الية .
تخيل الاتى : يوجد مدخل مباشر الى القسم المراد من ال Start Screen و توفير كل هذة الخطوات.
هذا التخيل هو ال Secondary Tile و هى تقوم بأنشاء مدخل من البرنامج للصفحة المراده مباشرة.
سوف نتحدث اليوم عن كيفية اضافة ال Secondary Tile فى تطبيقك لكن قبل ان نبدأ يجب ان نكون على علم بالمميزات التى تتيح لنا استخدام ال Secondary Tile
1)ال Secondary Tile تاخذك لصفحة بعينها و لكن هل بأمكان تطبيقك معرفة ما اذا كان هذا الصفحة مفتوحة من داخل التطبيق ام مفتوحة من ال Secondary Tile ؟؟ نعم
2)هل بامكانى الغاء ال Secondary Tile من داخل التطبيق ؟؟ نعم
3) هل بامكانى معرفة اذا كان المستخدم وضع ال Secondary Tile فى ال Start Screen كمدخل اخر للتطبيق ؟؟ نعم
4) هل يمكن ان استخدم ال Secondary Tile ك Live Tile فى تطبيقى ؟؟ نعم

كل هذة المميزات من الممكن ان تسخدمها داخل تطبيقك . فى هذا المقال سوف نكون معا Live Tile داخل ال Secondary Tile
1) افتح ال Visual Studio -> انشئ تطبيق Windows 8 جديد باستخدام لغة ال #C
2)قم باضافة صفحة اخرى لتكون هذة الصفحة هى الصفحة المراد فتحها من ال Secondary Tile و سميها SecondaryTilePage
3) قم باضافة Button ليذهب بك الى الصفحة الجديدة و اضف Event على ال button ليذهب بك الى الصفحة الاخرى

this.Frame.Navigate(typeof(SecondaryTilePage));

4)قم باضافة Button PinSecondaryTileButton فى ال SecondaryTilePage ليقوم بوضع ال Secondary Tile عند الضغط عليه و اضف Event عليه و قم باضافة TextBlock لتظهر علية ماذا يحدث الان فى التطبيق و سمية StatusTextblk

هناك بعض خصائص ال Secondary Tile مثل ال Small Logo فى هذا التطبيق سوف نستخدم ال Logos الموجودة فى التطبيق
و الان سوف نرى الكود المسؤول عن ال Secondary Tile قم باضافة فى ال Event Handler ل PinSecondaryTileButton

Uri logo = new Uri("ms-appx:///Assets/Logo.png");
Uri smallLogo = new Uri("ms-appx:///Assets/SmallLogo.png");                          
string tileActivationArguments = " PinnedAt : " + DateTime.Now.ToLocalTime().ToString();             
SecondaryTile secondaryTile = new SecondaryTile("Secondary_Tile11",                                                  "Secondary Tile Only",
"Secondary Tile Only",
tileActivationArguments,
TileOptions.ShowNameOnLogo | TileOptions.ShowNameOnWideLogo,                                                         logo);             
secondaryTile.SmallLogo = smallLogo;             
secondaryTile.ForegroundText = ForegroundText.Light;             
bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(GetElementRect((FrameworkElement)sender), Windows.UI.Popups.Placement.Below);             
if (isPinned)             
{                 
StatusTextblk.Text = "Pinned";             
}             
else             
{                 
StatusTextblk.Text = "Error";             
}

هناك ايضا ال Function المسؤلة عن GetElementRect

public static Rect GetElementRect(FrameworkElement element)
{       
GeneralTransform buttonTransform = element.TransformToVisual(null);
Point point = buttonTransform.TransformPoint(new Point());
return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
}

5)الان قم بتشغيل التطبيق و اذهب الى الصفحة الثانية و قم بالضغط على Pin Secondary Tile Button و اخرج لل Start Screen لترى

1

6) جاء وقت ان نضيف Live Tile لل Secondary Tile . هل تتذكر كيف قمنا باضافة Live Tile فى المقالات السابقة ؟؟ سوف نستخدم الطريقة الثانية و هى اضافة ال classes المساعدة و لمذيد عن ال Live Tile الرجاء الرجوع الى المقالين السابقين 🙂

7)قم باضافة SendLiveTileButton Button و اضف Event لة و فى هذا ال Event قم بكتابة الاتى

ITileSquareText04 squareContent = TileContentFactory.CreateTileSquareText04();
squareContent.TextBodyWrap.Text = "Sent Live Tile to a secondary tile!";
TileUpdateManager.CreateTileUpdaterForSecondaryTile("Secondary_Tile11").Update(squareContent.CreateNotification());

7) قم باضافة Reference لكل من ال TileContentFactory و TileUpdateManager
3

8)الان قم بتشغيل التطبيق و اذهب الى الصفحة الثانية و قم بتشغيل بالضغط على Send Live Tile Button لترى الاتى

2

هكذا قمنا باضافة Live Tile ل Secondary Tile ان كان لك اى سؤال ارجوك لا تتردد فى سؤالى 🙂
شكرا

2056910448_thanks_xlarge

Ibraheem Osama Mohamed
IbraheemOM@

Written by Ibraheem Osama Mohamed

July 5, 2013 at 12:09 pm

Posted in C#, Windows 8, Windows8, xaml

Web Service

leave a comment »

In this post I’ll illustrate how a simple web service work. But I first need to apologize for the bad graphics I made 🙂
Let’s take a look at this graphics. What we want to do ?? we want to connect our database to the client device , the database is hosted in a server and the client is a mobile device or whatever that have no DB , very small DB or you don’t want the client to store the Data (Cloud Concept). So what we want to do ?? to request data from the server (DB) to the client and how we are going to do that ?? using communication protocols (HTTP, SOAP, TCP etc….).
Web Services provide us a way to communicate with our clients using some protocols at the beginning we used SOAP (for more about SOAP Click Here) after that good people 🙂  figured out the restful (for more about restful Click Here) web service that communicate throw the HTTP protocol. This is a simple intro let’s get in-deep

Web ServiceI’ll start from the graphics from LTR (Left To Right an expression you should know)
1)We have our server that contains the Database (Oracle , SQL Server etc….)
2)The Web Service which connect the DB to the Client which maybe SOAP or Restful (preferred) unless you have a reason to use soap use restful
3)The Web Service is in control for the Database so we makes our query from the Web Service (Insert , Delete , Update , etc…)
4)The Web Service communicate with the client (Windows 8 , android , etc…) using messages this messages maybe XML or JSON (recommended because it takes less size and easier to config)

This is the science that you can implement on any OS (Windows Server , Linux) or using any technologies (asp.net , WCF , Java EE, php , etc..)
In this post I’ll list the technologies that will help you to make this arch.
1)Using Windows Server and SQL Server DB
2)For Web Service I’ll use restful so asp.net MVC web API is a good one OR implement a WCF restful Service 
3)In Communication Messages I’ll use JSON
4)And the Client it is up to you for me I’ll use Windows 8 , WP , android and blackberry the technologies I know 🙂

I hope that you can now Implement your own web service and the client application

2056910448_thanks_xlarge

ibraheem Osama Mohamed
@IbraheemOsamaMo

Written by Ibraheem Osama Mohamed

February 21, 2013 at 1:19 pm

Consume Soap based JSON Web Service in Windows 8 HTML Metro Style Application

with 2 comments

Before start in the post I should mention something that Yasser Makram posted post about HTMl and Web Services before me :).
You can download my the Sample from the MSDN from Here
Consuming a web service in a non .net language my seen a little harder comparing to .net language. so you may find it harder to consume the web service in HTML .In Windows 8 there something called Windows Runtime Component  which enables to use  VB , C# or C++ Class in you metro Style Application. That’s the point we will consume the web service in C# in an easy way and use C# function tot returns the web service result to JavaScript application.
The sent data will be in JSON Format. Windows 8 doesn’t have a reference to system.json library so you have do download it from NuGet

Let’s Start
1)Add a New Windows 8 JavaScript black Application (The Main Application)

2)In The Solution Add a New WCF Application (The Web Service)

3)Add a New Windows Runtime Component (To consume the web service in an easy way then use it in JavaScript )

4)In the WCF Application open  the  IService1.cs and changed the interface functions to

[OperationContract]

        string GetJSONData();

Read the rest of this entry »

Written by Ibraheem Osama Mohamed

September 8, 2012 at 6:36 pm

Access a Control(Button,TextBox) in UserControl in Xaml from another Page

with 4 comments

After adding the userControl in our Xaml code how can we access it’s controls ??  What we need is a reference to the control.

From the last post we added a userControl called flyout (in the last example there is no textbox in the flyout called NameTextBox this is just an example but there is a SaveButton and deleteButton)

            TextBox nameTextbox = flyout.FindName(“NameTextBox”) asTextBox;

            string name = nameTextbox.Text;

 

            Button addbutton = flyout.FindName(“SaveButton”) asButton;

            Button deletebutton = flyout.FindName(“deleteButton”) asButton;

            addbutton.Click += (a, b) => { EnteryStoryboard.Begin(); };

            deletebutton.Click += (a, b) => { EnteryStoryboard.Begin(); }; 

but take care of you write the name wrong in the FindName method you’ll get a null reference exception

Written by Ibraheem Osama Mohamed

July 31, 2012 at 4:03 pm

Windows 8 Share Contract

leave a comment »

Is it easy to add a Share contract in Windows 8 ? There is nothing more simple. This post will help you to implement a Share contract for a text and an image in your application

1)Open Visual Studio -> New Metro black Application.
2)Open the MainPage.xaml -> add an Image and a TextBox
3)Open the MainPage.xaml.cs Add the following references

using Windows.ApplicationModel.DataTransfer;

using System.Text;

using Windows.Storage.Streams;

4)In the OnNavigatedTo event add the following code

protected override void OnNavigatedTo(NavigationEventArgs e)

{

     DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;

}

5)Now you need to add a method for OnDataRequested

void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)

        {

            //This is the code for sharing a Text

            var request = args.Request;         

            request.Data.Properties.Title = textbox1.Text;//or any text you want to share

            request.Data.Properties.Description = “This is the text of the textbox I’d like to share with you”;           

            var body = “Now you can make search contract as you like you can add many thing and make any application that you are using to search to use this text or image”;         

            request.Data.SetText(body);

 

            //This is the code for sharing an Image

            // var reference = RandomAccessStreamReference.CreateFromUri(image1.BaseUri);

            var reference = RandomAccessStreamReference.CreateFromUri(newUri(newUri(“ms-appx:///”), “Assets/LightGray.png”));

            request.Data.Properties.Thumbnail = reference;

            request.Data.SetBitmap(reference);

 

        }

6)And to make your application execute safely remove the OnDataRequested event when closing this application or moving to another application. This code make this mission

protected override void OnNavigatedFrom(NavigationEventArgs e)

        {           

            DataTransferManager.GetForCurrentView().DataRequested -= OnDataRequested;       

            base.OnNavigatedFrom(e);

        }

7)Run The application and you’ll get the result.

Ibraheem Osama Mohamed
@IbraheemOsamaMo

Written by Ibraheem Osama Mohamed

July 22, 2012 at 5:03 pm

The application called an interface that was marshalled for a different thread.

with 3 comments

This error Occur when you try to access an object in the UI from another task or thread in Windows 8 like if you are trying to change the text of a TextBox in a task (If you have the same problem in WPF or in WP7 check this post)
This post will help you to solve the problem and will help if you are developing Metro Apps
Lets start
1)Add new empty Metro Style App.
2)Add a Button and a TextBox and assign a click event for the Button.
3)Declare a Task and Initialize it , initialize an action for the task and write a function for the action.

this.Loaded += (A, b) =>

{

Action a = newAction(func);

task = new System.Threading.Tasks.Task(a);

};

public void func()

{

textbox1.Text = “Hello World”; //this code will not run this code is just for learning (Wrong Code)

}

4)In the Button Click Event start the task

task.Start();

5)Run the Code and in the Click event you’ll get this error.The solution for this error is to call a Dispatcher for the UI element and invoke the RunAsync method which take 2 args CoreDispatcherPriority(High,Medium,Low) and a Delegate.

textbox1.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { textbox1.Text = “Hello World”; });

Here is the Complete Code 🙂

System.Threading.Tasks.Task task;

   publicvoid func()

        {

            textbox1.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { textbox1.Text = “Hello World”; });

        }

        public MainPage()

        {

            this.InitializeComponent();

            this.Loaded += (A, b) =>

            {

                Action a = newAction(func);

                task = new System.Threading.Tasks.Task(a);

            };

        }

        protectedoverridevoid OnNavigatedTo(NavigationEventArgs e)

        {

        }

        privatevoid Button_Click_1(object sender, RoutedEventArgs e)

        {

            task.Start();

        }

I hope that you get the point 🙂

Ibraheem Osama Mohamed
@IbraheemOsamaMo

Written by Ibraheem Osama Mohamed

June 24, 2012 at 10:29 pm

%d bloggers like this: