Sunday, May 30, 2010

.NET Fundamentals 2

Changes to which portion of version number indicates an incompatible change?
Major or minor. Changes to the major or minor portion of the version number indicate an incompatible change. Under this convention then, version 2.0.0.0 would be considered incompatible with version 1.0.0.0. Examples of an incompatible change would be a change to the types of some method parameters or the removal of a type or method altogether. Build. The Build number is typically used to distinguish between daily builds or smaller compatible releases. Revision. Changes to the revision number are typically reserved for an incremental build needed to fix a particular bug. You'll sometimes hear this referred to as the "emergency bug fix" number in that the revision is what is often changed when a fix to a specific bug is shipped to a customer.

What is side-by-side execution? Can two application one using private assembly and other using Shared assembly be stated as a side-by-side executables?
Side-by-side execution is the ability to run multiple versions of an application or component on the same computer. You can have multiple versions of the common language runtime, and multiple versions of applications and components that use a version of the runtime, on the same computer at the same time. Since versioning is only applied to shared assemblies, and not to private assemblies, two application one using private assembly and one using shared assembly cannot be stated as side-by-side executables.

Why string are called Immutable data Type ?
The memory representation of string is an Array of Characters, So on re-assigning the new array of Char is formed & the start address is changed . Thus keeping the Old string in Memory for Garbage Collector to be disposed.

What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

What's the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

How do assemblies find each other?
By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

How does assembly versioning work?
Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.

What is garbage collection?
Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

Why doesn't the .NET runtime offer deterministic destruction?
Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap. Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

Is the lack of deterministic destruction in .NET a problem?
It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

What is serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization / Deserialization is mostly used to transport objects (e.g. during remoting), or to persist
objects (e.g. to a file or database).

Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field.
This property can be used to serialize a dictionary object, which is always a pain when it comes to serialization. We can create an array of key value pair and whenever it comes to serialize dictionary, we can return that array and while deserializing we can convert it back to dictionary.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

What are attributes?
Essentially attributes are a means of decorating your code with various properties at compile time.  This can be passive, such as marking a class as  Serializable with the SerializableAttribute, or it can take a more active role, such as the  MarshalAsAttribute which tells the runtime how to pass data between managed and unmanaged code. In the former case when you try serializing an object, the runtime checks to see if the object has the SerializableAttribute applied to it.  In this case the attribute is nothing more than a flag to let the runtime know that the classes author gave the OK for serialization (since this could expose some sensitive data to someone who should see it).In the latter case a more active role is taken.  The MarshalAsAttribute when applied to a field in a struct will tell the runtime what type of data the .NET type should be formatted as when it is sent to unmanaged code, and what type it should convert the return value from when it comes back from the unmanaged code. All attributes inherit from System.Attribute and are classes just like 90% of the framework.  This also means that what you can do with a class you can do with an attribute; given an instance of an attribute you can get its underlying type.  You can also create attributes at runtime with the Reflection.Emit classes and bind them to classes you have built with the Emit package.

Saturday, May 29, 2010

.NET Fundamentals 1

What platforms does the .NET Framework run on?
The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home.
The Mono project is attempting to implement the .NET framework on Linux.

What is the CLR?
CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language.
CLR includes these features:
  • Common type system
  • Just in time compiler
  • Security Support
  • Garbage collection and memory management
  • Class loader
  • COM interoperability
CLR runtime manages memory,thread execution, code safety verification, compilation and other system services. These features are intrinsic to managed code that runs in the common language run time.
What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services.

What is the CTS?
CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

What is the CLS?
CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language.
In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class.

What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

What does 'managed' mean in the .NET context?
The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.

Managed code: Code that has its execution managed by CLR. It is the responsibility of framework to provide memory management, security etc.The necessary information is encoded in intermediate language and associated metadata. Every language which is providing managed code will emit a PE file having IL and metadata. Now its responsibility of CLR to convert this IL code into executable, which is done by JIT compiler. CLR for different OS can be different. So the same IL will get converted into different executable code.

Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. It can only be accessed by managed code.

What is reflection?
Reflection is the mechanism of discovering class information solely at run time. All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries. Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember ) , or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

What is the difference between Finalize and Dispose (Garbage collection) ?
Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object. In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object.
Dispose can be called even if other references to the object are alive. Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.

What is Partial Assembly References?
Full Assembly reference: A full assembly reference includes the assembly's text name, version, culture, and public key token (if the assembly has a strong name). A full assembly reference is required if you reference any assembly that is part of the common language runtime or any assembly located in the global assembly cache.
Partial Assembly reference: We can dynamically reference an assembly by providing only partial information, such as specifying only the assembly name. When you specify a partial assembly reference, the runtime looks for the assembly only in the application directory.
We can make partial references to an assembly in your code one of the following ways:
-> Use a method such as System.Reflection.Assembly.Load and specify only a partial reference. The runtime checks for the assembly in the application directory.
-> Use the System.Reflection.Assembly.LoadWithPartialName method and specify only a partial reference. The runtime checks for the assembly in the application directory and in the global assembly cache

.NET fundamentals 0

1.What do you know about BCL?
The BCL (Base Class Library) is a combination of classes or we can say that it’s a library of functionalities and types available to all languages that used in .NET Framework. To make the programmer job more easier dot net gave a advantage to includes the BCL in order to collect a large number of common functions, just like to read a file and write to file, graphic rendering, database interaction, and XML document manipulation at one place . The scope of this is large and standard libraries for most other languages, including C++, and would be comparable in scope to the standard libraries is just like Java. The BCL is sometimes incorrectly referred to as the Framework Class Library (FCL), which is a superset including the Microsoft namespaces.

2.In Assembly which work as GacBrowser ?
The GACPicker class allows the user to select an assembly from the Global Assembly Cache. It does this by looking at the filesystem representation of the GAC, since there appears to be no actual API in the current .NET environment.

3.What is purpose of Assembly Linker or define SDK Tool in .NET Framework?
In .NET whole the working should be with the helps of DLLs.So all of Visual Studio .Net compilers generate assemblies or u can say dll.If we want to create an assembly with manifest of a module.We can also put this assembly in separate file.This AL tool generate a file with an assembly manifest from modules or resources files.The syntax of using Al.exe is   al [sources] [options]
This tool helps in creating multi-file assembly outside Visual Studio .Net .This multi file can contain modules that are written in different language in one application.

4.Does .NET CLR and SQL SERVER run in different process?
Dot Net CLR and all .net application and Sql Server run in same process or we can say that that on the same address because there is no issue of speed because if these two process are run in different process then there may be a speed issue created one process goes fast and other slow may create the problem.

5. .NET framework stack:




6.What are similarities between Class and structure ?
Following are the similarities between classes and structures :-
√ Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
√ Structures and classes can implement interface.
√ Both of them can have constructors with and without parameter.
√ Both can have delegates and events.

7.What is Assembly name and name space?
An assembly is a logical unit of code. Physically it may exist as dll or an exe. which can contain one or more files and they can be any file types like image files, text files etc. along with DLLs or EXEs.When you compile your source code by default the exe/dll which is generated is actually an assembly and every assembly file contains information about itself which is called as Assembly Manifest. Namespace is an abstract container providing context for the items it holds and allows disambiguation of items having the same name (residing in different namespaces. It can also be said as a context for identifiers. So under a namespace you can have multiple assemblies.

8.In .NET Compact Framework, can I free memory explicitly without waiting for garbage collector to free the memory?
.NET Compact Framework come with CLR which perform automatic garbage collector to free the memory without using destructor (perform garbage collector when is declare)

Flex 4

1.myTree appears just fine but why can't I access the node attributes?
Select a node in your myTree. In ActionScript, you can reference this node by using the following code:
myTree.selectedNode;
To access the attributes of the node, use the treeDataProvider API. These methods will work for any formatdataProvider item, which might be an object, array, or XML node. The following example might work:
myTree.selectedNode.attributes.myAttribute
But the following example is far more reliable:
myTree.selectedNode.getProperty("myAttribute");

2.How do I pass parameters to a pop-up window? Three different ways to pass data into a title window. It uses the initobj to pass in several built-in properties plus two user defined properties. One is a simple string, the other is a reference to the main application that can
be used for binding. Note the variable that holds the application reference is
typed to the name of the application. this is critical for binding to work
correctly.

3.How do I run Flex as a service?
Flex is not a server that you deploy and run. It is simply deployed as part of your web application. So it will work, no matter which web container you are using: Tomcat, JRun 4, WebLogic, and so forth. To learn how to deploy Tomcat, JRun 4, or any other Java server as a service, refer to the appropriate documentation for the server you are using.

4.How do I get Flex to query my database? Flex does not have any native database integration functionality. You must have your own server-side
tier that provides the database-access tier and sends the data back to Flex through one of the
following protocols:
• RemoteObjects: This is the fastest. It communicates with server-side EJBs or POJOs using AMF, a binary compressed format.
• HTTPService: This one uses the HTTP protocol. Sources can be JSP, ASPx, .NET, or any URL that returns HTTP.
• WebService: This is the slowest. It uses the SOAP protocol. Sources can be .NET or any web service

5.How do I make synchronous data calls?
You cannot make synchronous calls. Youmust use the result event. No, you can't use a loop, setInterval, or even doLater. This paradigm is quite aggravating at first. Take a deep breath, surrender to the inevitable, resistance is futile.
There is a generic way to handle the asynchronous nature of data service calls, called ACT (Asynchronous Call Token). Search for this in the Developing Flex Applications LiveDocs for a full
description.
Here it is in a nutshell. This example uses HTTPService but will be similar for RemoteObject and WebService:
1. Create a function to handle the data return, likeonResult().
2. In the HTTPService tag, put this function name in theresult property and pass "event" in too.
3. Invoke the call in the script: //invokes the call to the HTTP data service
var oRequestCallbject = app.mxdsGetData.send(oRequest);
//Next, define a string to identify the call. We will use this string value
in the result handler.
oRequestCall.MyQueryId = "WhateverIWanttoUseToIdentifyThisCall" ; //Yes, you CAN set this AFTER you invoke send()
4. In the result handler, which will be called every time the data service call returns, identify what the returned data contains, as follows: var callResponse = oEvent.call; //get the call object
//gets the value of this property you set in the call
var sQueryId = callResponse.MyQueryId; //will be
"WhateverIWanttoUseToIdentifyThisCall";
trace(sQueryId);
You can use thesQueryId value in a switch to do the correct processing. Alternatively, you can pass reference to a handler function directly.

6.When I have only a single record, why doesn't it appear in my DataGrid?
This is a known issue that is caused by the inability of Flex to differentiate between an object and an
array with a single row. The solution is toalways usetoArray(), as in the following examples:
In MXML:
{mx.utils.ArrayUtil.toArray(modelAccidents1.accidents.accident)}
The inline format: dataProvider={mx.utils.ArrayUtil.toArray(testSrv.result.result.error)}
In ActionScript: myControl.dataProvider = mx.utils.ArrayUtil.toArray(testSrv.result.result.error)

7.Why are the columns in my DataGrid in some strange order?
The order is typically the reverse of the order in which they were added. If you need a specific order, specify that and many other good things by usingDataGridColumn tags.

8.Can I embed HTML in my Flex application?
Flex supports a limited subset of HTML in itsTextArea and some other text-related classes.

9.Are there frameworks available for Flex?
Yes there are:
• Cairngorm:http
• FlexUnit
• SynergyFLEX:http
• ARP
• AsUnit

10.Is vertical text possible in Flex?
Yes, that is possible. You have to embed the font outlines and then use the_rotation property of the control. For example, you can use the Label_rotation property. But you would need to embed the font if you want to rotate a Label, TextInput, or TextArea:

11. Flex component life cycle:
Initialization Stage :
a) Construction Stage (Initialization Phase): In this stage of initialization Phase, the constructor of the component is called by component tag in MXML
or usingnew operator . We can use this stage to;
1) Set some of initial values for the component properties.
2) To add event listeners to the component.
3) And initialize the other objects.

b) Configuration Stage (Initialization Phase): This stage occur only once in component life cycle. During this step the values assigned for properties of the component using setters are set internally to refer them later in configuration of component.
c) Attachment Stage (Initialization Phase): This stage of Initialization Phase gets triggered when component is added to the display list using either addChild(), addChildAt() Or component created in MXML tags. In this stage the components parent is defined because the component is now added to the display list. When this component is added to display list it calls initialize () method to initiate the next stage of this phase, i.e. Initialization Stage.
d) Initialization Stage (Initialization Phase): After component is attached (Attachment Stage) to the display list, initialization Stage starts. This is
important Stage of the component life cycle. This is responsible to create children objects of the component,
sizing and placing the component and its children, and applying the property, style values to the component.
During this stage following steps occurs;
Step1: Dispatch preinitialize event.
Step2: Callscreat eChildren() method to create children of the component.
Step3: DispatchInitia lize event
Step4:Inval idation: Marks the component for Invalidation which results the component to go with methods
invalidateProperties(), invalidateSize()and invalidateDisplayList(). (We see more about Invalidation after some lines) Step5:Val idation: Invalidation of last step results to validation methods like commitProperties(), measure() andupdateDisplayL iIst().(we see more about Validation after some lines)
Step6: Dispatch creationComplete event.

Flex 3

1.What are the methods called when a UI component is intialized?
createChildren()

2.What is a drag manager? The DragManager class manages drag and drop operations, which let you move data from one place
to another in a Flex application. For example, you can select an object, such as an item in a List
control or a Flex control, such as an Image control, and then drag it over another component to add it
to that component.
All methods and properties of the DragManager are static, so you do not need to create an instance of it. All Flex components support drag and drop operations. Flex provides additional support for drag and drop to the List, Tree, and DataGrid controls. When the user selects an item with the mouse, the selected component is called the drag initiator. The image displayed during the drag operation is called the drag proxy. When the user moves the drag proxy over another component, thedragEnter event is sent to that component. If the component accepts the drag, it becomes the drop target and receivesdragOver, dragExit, and dragDropevents. When the drag is complete, adragComplete event is sent to the drag initiator.

3.How do you call javascript from Flex?
The ExternalInterface class is the External API, an application programming interface that enables
straightforward communication between ActionScript and the Flash Player container– for example,
an HTML page with JavaScript. Adobe recommends using ExternalInterface for all JavaScript-
ActionScript communication.
You can call an ActionScript function in Flash Player, using JavaScript in the HTML page. The
ActionScript function can return a value, and JavaScript receives it immediately as the return value
of the call.
This functionality replaces thefscommand() method. The ExternalInterface class requires the user's web browser to support either ActiveX® or the
NPRuntime API that is exposed by some browsers for plug-in scripting. Even if a browser and
operating system combination are not listed above, they should support the ExternalInterface class if
they support the NPRuntime API.
Note: When embedding SWF files within an HTML page, make sure that theid andname attributes of theobject andembed tags do not include the following characters: . - + * / \
From ActionScript, you can do the following on the HTML page:
 • Call any JavaScript function.
• Pass any number of arguments, with any names.
• Pass various data types (Boolean, Number, String, and so on).
 • Receive a return value from the JavaScript function. From JavaScript on the HTML page, you can:
• Call an ActionScript function.
• Pass arguments using standard function call notation.
• Return a value to the JavaScript function.
Flash Player does not currently support SWF files embedded within HTML forms.

4.How do you use a repeater?
The Repeater class is the runtime object that corresponds to the mx:Repeater> tag. It creates
multiple instances of its subcomponents based on its dataProvider. The repeated components can be
any standard or custom controls or containers.
You can use the mx:Repeater> tag anywhere a control or container tag is allowed, with the exception of the mx:Application> container tag. To repeat a user interface component, you place its tag in the mx:Repeater> tag. You can use more than one mx:Repeater> tag in an MXML document. You can also nest mx:Repeater> tags.
You cannot use the mx:Repeater> tag for objects that do not extend the UIComponent class. MXML Syntax
 The  Repeater> class has the following properties: 
mx:Repeater Properties id="No default" childDescriptors="No default" count="No default" dataProvider="No default" recycleChildren="false|true" startingIndex="0" Events repeat="No default" repeatEnd="No default" repeatStart="No default" >

5.What does calling preventDefault() on an event do? How is this enforced? public function preventDefault():void Cancels an event's default behavior if that behavior can be canceled. Many events have associated behaviors that are carried out by default. For example, if a user types a
character into a text field, the default behavior is that the character is displayed in the text field.
Because theTextEvent.TEXT_INPUT event's default behavior can be canceled, you can use the preventDefault() method to prevent the character from appearing. An example of a behavior that is not cancelable is the default behavior associated with the Event.REMOVED event, which is generated whenever Flash Player is about to remove a display object from the display list. The default behavior (removing the element) cannot be canceled, so the preventDefault() method has no effect on this default behavior. You can use theEvent.cancelable property to check whether you can prevent the default behavior associated with a particular event. If the value ofEvent.cancelable istrue, then preventDefault() can be used to cancel the event; otherwise, preventDefault() has no effect.
![CDATA[ private function textArea_textInput(evt:TextEvent):void
{ if (evt.text == "\n")
{ evt.preventDefault(); }
} ]]>
/mx:Script>
mx:TextArea id="textArea" verticalScrollPolicy="on" width="160"
height="120" textInput="textArea_textInput(event);">
mx:text>The quick brown fox jumped over the lazy dog.
/mx:text>
/mx:TextArea>

6.LifeCycle of Flex-application??

initializedproperty
initialized:Boolean[read- wri te]
A flag that determines if an object has been through all three phases of layout: commitment, measurement, and layout (provided that any were required).
Ex:
    ?xml version="1.0" encoding="utf-8"?>
    mx:Applicationx mlns:mx="http://www.adobe.com/2006/mxml"     layout="absolute"width="349" height="319"     viewSourceURL="../files/LifeCycleEventsTutorial.mxml"     preinitialize="recordEvent(event)" initialize="recordEvent(event)"     creationComplete="recordEvent(event)"     applicationComplete="recordEvent(event)">
     mx:Script>
     ![CDATA[ importmx.ev ents.FlexEv ent;
     importflash.ut ils.getTimer;
     [Bindable]
     privatevarreportTxt:String= "";
     privatefu nctionrecord Event(event:F lexEvent):void
     { reportTxt += (event.type + " event occured at " +      flash.utils.getTimer() +" ms" +"\n"); } ]]>
     /mx:Script>
     mx:Panelx="0" y="0"width ="349"heigh t="319" layout="absolute"      title="Life Cycle Events">
     mx:TextAreax="10" y="10"width ="309"heigh t="259" editab le="false"      id="txtReport" text="{reportTxt}"/>
     /mx:Panel>
     /mx:Application>
7.Can I dynamically instantiate a WebService or HTTPService in ActionScript?
Flex 1.5 does not support this. First declare the tags in MXML and then manipulate the URLs, request objects, and so forth using ActionScript.

8. Can I load CSS style sheets dynamically at runtime?
Dynamic loading of CSS files is not supported in Flex. CSS in Flex is processed on the server side during MXML compilation rather than on the client side at runtime. There is a trick though: A CSS file can be compiled into a separate SWF file and loaded dynamically into the application using the Loader component.

9.When I setvisible="false", the component still takes up space and appears in the tab order. Why is that?
You can often achieve the "display=none" effect by setting the height/width to zero when you set it invisible, and then set it back to a fixed value or toundefined when you make it visible again.

10.Why are my ValueObject member variables undefined in the results from my RemoteObject requests?
A.Flash Player deserializes objects in a special order that can confuse developers used to object serialization from other RPC systems. When a strongly typed object is returned to the player, it first creates an instance from the prototype of the registered class without calling the constructor. It then
populates the object with the properties sent in the result. Finally, it calls the constructor without arguments. If your ValueObject constructor expects arguments to initialize an instance, be sure to check whether arguments were actually sent to the constructor before overriding member variable values.

11.Why do strongly typed objects appear as "undefined" in the NetConnection Debugger?
The NetConnection Debugger is an old utility from the early days of Flash Remoting that some developers still find useful. It has an issue, however, displaying types that have been registered with Object.registerClass(). If your Flex server is installed locally, we suggest enabling server-side "debug" level logging in /WEB-INF/flex/gateway-config.xml to watch the raw trace information in the Flex server console/logs from the AMF Gateway as it processes your RemoteObject requests. Flex Builder also includes a Network Debugger that allows you to monitor AMF traffic.

12.How do I get access to the J2EE session from my RemoteObjects? The AMF Gateway provides access to the currentHttpServletRequest instance in a thread local variable. The session can be obtained from the request, as follows: flashgateway.Gateway.getHttpRequest().getSession();

13.Can I resize the Internet Explorer browser window from Flex?
UsegetURL() to communicate with JavaScript in the HTML wrapper: getURL('javascript:window.resizeTo(1050,900)');

14.Can Flex applications communicate with each other on the client?
See theLocalConnection API in the documentation.

15.Is double-clicking supported on various components?
A.Unfortunately, double-clicking is not supported by default. If you wish to add this functionality to, say, a List or DataGrid component, you will have to add the following ActionScript 2.0 code to your application:
var someTimestamp:Number;
public function doubleClickHandler( evt:Object ):Void {
var now = getTimer();
// we got a double-click
if( ( now - someTimestamp ) < 500 ) {
// do something here ... }
someTimestamp = now; }

16.Why are there errors with the macromedia.css.LocatorParser class and WebLogic? WebLogic ships with its own version of the fop.jar, which in turn includes the batik.jar, which is older and breaks Flex. To resolve this issue, remove the fop.jar from the CLASSPATH in the startWebLogic.cmd file. This may apply to non-WebLogic servers as well, where batik.jar was included.

17.What does "The URL is not in the Proxy's whitelist" mean?
The whitelist is a security feature in Flex that requires you to define explicitly which URLs a data service call can access.
You set this by editing the following file: ...\[flexroot]\WEB-INF\flex\flex-config.xml
There are three sections, one each for WebService, HTTPService, and RemoteObject. Be sure you edit the correct section! Each has a subsection which contains nodes. To enable a URL for access by a Flex dataService call, enter that URL between the tags. For development phaseonly, you can allow global access with the wildcard rows. The flex-config file is heavily commented. Open it up and you will see more detailed instructions there.

18.Sometimes, if I don't move the mouse, "click" and "mouseDown" don't work. Why is that?
This is a focus issue with Flash Player; usually when the UI changes "underneath" the mouse pointer, as in a ViewStack navigation where the buttons are in the same screen location.

19. Why ismyTreeNode.label ormyTreeNode.attributes.label undefined?
Make sure you use theTreeDataProvider methods to modify a node. Don't rely on the node being XML. For example, the above should bemyTreeNode.getProperty("label") instead.

20.When I add or modify an item in my dataProvider, why doesn't it show up in my DataGrid?
Low-level methods likeArray.push() or myArray[0] = "whatever" do not cause the
dataProvider'smodelChanged event to fire. When you work with a dataProvider, it is always best to use the dataProvider API. In the above example, you might code:myDataProvider.addItem(myItemObject) to add an item or use editField() to modify a value programmatically. Alternatively, you can callmyDataProvider.modelChanged yourself or reassigndataProvider to the control, as follows: myDataGrid.dataProvider = myDataProvider;


Flex 2

1.what is MVC and how do you relate it to flex apps?
A : (Separation of concerns) The goal of the Model-View-Controller (MVC) architecture is that by
creating components with a well-defined and limited scope in your application, you increase the
reusability of the components and improve the maintainability of the overall system. Using the MVC
architecture, you can partition your system into three categories of components:
* Model components Encapsulates data and behaviors related to the data.
* View components Defines your application's user interface.
* Controller components Handles the data interconnectivity in your application.

2.what is state? what is the difference between states and ViewStack?
A : The State class defines a view state, a particular view of a component. For example, a product
thumbnail could have two view states; a base view state with minimal information, and a rich view
state with additional information. The overrides property specifies a set of child classes to add or
remove from the base view state, and properties, styles, and event handlers to set when the view state
is in effect.
You use the State class in the states property of Flex components. You can only specify a states
property at the root of an application or a custom control, not on child controls.
Diff :
* View Stack is to handle different MXML file eg TAB control and states is the transition within
single MXML file.
* ViewStack should be used were there is complete change in the controls used and States should be
used when you just want to add or remove a
few components based on certain conditions.
* ViewStates are virtual state of an existing page apearing at an instance i.e. only one state can be
shown at a time
while viewStack are collection of different view containers which can be shown at a time

3.how does item renderer work? How do I add item renderer at runtime?
A : Each list control has a default mechanism for controlling the display of data, or view, and lets
you override that default. To override the default view, you create a custom item renderer.
Note: With reusable inline item renderers you use data binding to bind to the item renderer. When
you use a component as an item renderer, you do not use data binding but specify the name of the
custom component to use as an item renderer.
Add itemrendrer at run time: Create the basic item renderer. One of the things I needed to accomplish
with my item renderer was the ability to add it to different columns (ie the dataField was not always
the same). This meant I needed a way from within the renderer to determine what column it was
bound to so I could get and display the correct data. To do this the renderer needs to implement the
IDropInListItemRenderer. This interface allows the renderer to have access to information about the
list and column it is in via the BaseListData and DataGridListData classes. The DataGridListData
gives you everything you need to get the data required to make a flexible, reusable renderer.
To Modify itemrenderer at runtime we Need to use mx.core.ClassFactory. Basically, in order to
change a Flex itemRenderer at runtime, you need to cast it to a type ClassFactory.

4.What keyword allows you to refer to private variables of a class?
A : private keyword , this keyworld (?)

5.how polymorphism works on actionscript?
A:
class UnpaidIntern extends Employee
{
    override public function receivePayment():Number
    { return 0;
    }
}
class Manager extends Employee
{
    override public function receivePayment():Number
    { return baseSalary*3;
    }
}
class Engineer extends Employee
{
    override public function receivePayment():Number
    { return this.baseSalary*2;
    }
}
class Employee
{
    internal var baseSalary:Number = 1000;
    public function receivePayment():Number
    {
        return this.baseSalary;
    }
}

6.how do you overload functions in actionscript?
A : Method overloading using namespaces. (?)

7.what is dynamic keyword used for?
A: Dynamic classes, which allow you to programmatically add new properties and behavior to classes during the run-time. Just add the magic keyword dynamic to the class definition:
dynamic class Person {
var name:String;
}
Now let’s add dynamically two variables name and age and the function printme() to the object of
type Person:
Person p= new Person();
p.name=”Joe”;
p.age=25;
p.printMe = function () {
trace (p.name, p.age);
}p.printMe(); // Joe 25


8.what are sealed classes ?
A : A sealed class possesses only the fixed set of properties and methods that were defined at
compile-time; additional properties and methods cannot be added. This makes stricter compile-time
checking possible, resulting in more robust programs.

9 what are runtime shared libraries?
Macromedia Flex 1.5 you can build runtime shared libraries (RSLs) that can be individually loaded,
cached, and used by multiple applications.
Use Flex 3 runtime-shared-libraries (RSLs) to reduce the size of your applications and thereby
reduce the time required to download the application. RSLs are just SWF files whose code is used as
a shared library between different application SWF files. There are two kinds of RSLs, signed and
unsigned. Signed RSLs are libraries that are signed by Adobe and may be stored in the Flash Player
Cache, which can be accessed by applications from any domain. This means if your application is
using a signed RSL, the RSL may not even need to be downloaded if the RSL is already in the Flash
Player Cache. The signed RSL may have been put into the Flash Player Cache by visiting another
web site that was using the same signed RSL. Signed RSLs have a "swz" extension.
Unsigned RSLs are normal SWF files and are not loaded into the Flash Player Cache. Instead, these
RSLs rely on the browser's cache to keep them from being downloaded.

10.What is cairnghorm ? how do you use it?Have you worked with Cairnghorn?
A : Cairngorm is the lightweight micro-architecture for Rich Internet Applications built in Flex or
AIR. A collaboration of recognized design patterns, Cairngorm exemplifies and encourages best-
practices for RIA development advocated by Adobe Consulting, encourages best-practice leverage of
the underlying Flex framework, while making it easier for medium to large teams of software
engineers deliver medium to large scale, mission-critical Rich Internet Applications.
The benefits of the Cairngorm architecture are realized when developing complex RIA applications
with multiple use-cases and views, with a team of developers, and with a multi-disciplinary
development team that includes designers as well as creative and technical developers.
How is the MVC pattern carried out in a Flex + Cairngorm application?

- Model:???? Role of the ModelLocator & Model Objects
- View:???? Role of View Components & Event Objects
- Controller: Role of the FrontController & Command Objects

11.What keyword allows you to implement abstraction better?
A: Flex does not support abstart class directly. (?)

12.What design patterns have you used? in Actionscript and java?
A:
1. Creational Pattern
    * Factory Method Pattern
    * Singleton Pattern
2. Structural Patterns
    * Decorator Pattern
    * Adapter Pattern
    * Coposite Pattern
3. Behavioral Patterns
    * Command Pattern
    * Observer Pattern
    * Template Metod Pattern
    * State Pattern
    * Strategy Pattern
4. Multiple Patterns
    * MVC Pattern
    * Symetric Proxy Pattern

13.Explain how binding works in mxml components.
A: Binding in MXML
Lets look at the following code…
mx:TextInput id=”ti1?/>
mx:Label id=”label1? text=”{ti1.text}”/>
Here you are binding the text property of the TextInput to the label. So whatever you type in the
textInput automatically reflects in the label. That’s the power of Binding…
The best practice for defining components that return information back to the main application is to
design the component to dispatch an event that contains the return data. In that way, the main
application can define an event listener to handle the event and take the appropriate action. You also
use events in data binding. The following example uses the Bindable metadata tag to make
useShortNames a bindable property. The implicit setter for the useShortNames property dispatches
the change event that is used internally by the Flex framework to make data binding work.

14.What’s the difference between ChangeWatcher. watch, and BindingUtils.bindProperty?
A: ChangeWatcher: Acts like the watch on AS2. It watches a variable for changes and when something happens fires an event. Make sure you call the canWatch to ensure that you can watch it!
There are 3 ways to specify the second parameter, the chain.
1. A String containing the name of a public bindable property of the host object.
ChangeWatcher.watch(this, "myvar", handler)
2. An Object in the form: { name: property name, access: function(host) { return host[name] } }.
The Object contains the name of a public bindable property, and a function which serves as a getter for that property.
ChangeWatcher.watch(this, { name:"myvar", getter: function():String { return "something" }},
handler);
3. A non-empty Array containing any combination of the first two options. This represents a chain
of bindable properties accessible from the host. For example, to watch the property host.a.b.c, call
the method as: watch(host, ["a","b","c"]
BindingUtils.bindProperty:Works pretty much the same way as the watch, but instead of having to handle and event it allows you to immediately bind two properties one-way.
The first two parameters are for the the target, the second parameters are the triggers.
BindingUtils.bindProperty( this, "va1", this, "var2");
Note : Make sure you add the flex framework.swc to your project Library Path to have access to the mx.binding.util class.

15.Why would you want to keep a reference to a ChangeWatcher and call unwatch()?
A: So we can reattach the watcher again & We can change the source object (of changewatcher) by reset method.
The ChangeWatcher class defines utility methods that you can use with bindable Flex properties. These methods let you define an event handler that is executed whenever a bindable property is updated. unwatch () method: Detaches this ChangeWatcher instance, and its handler function, from the current host. You can use
the reset() method to reattach the ChangeWatcher instance, or watch the same property or chain on a
different host object.
public function unwatch():void

16.How do you add event listeners in mxml components. Now AS3 components?
A:
* addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
* removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
* dispatchEvent(event:Event):Boolean
* hasEventListener(type:String):Boolean
* willTrigger(type:String):Boolean

17.What does calling preventDefault() on an event do? How is this enforced?
A: Cancels an event's default behavior if that behavior can be canceled.. For example, the
doubleClick event has an associated default behavior that highlights the word under the mouse
pointer at the time of the event. Your event listener can cancel this behavior by calling the
preventDefault() method.
You can use the Event.cancelable property to check whether you can prevent the default behavior
associated with a particular event. If the value of Event.cancelable is true, then preventDefault() can
be used to cancel the event; otherwise, preventDefault() has no effect.

18.Explain the lifecycle of a Cairngorm action.
A: Here’s a normal flow of operations and the Cairngorm classes that are exercised.



When the user takes some sort of action on the view, such as clicking a button, the view dispatches a CairngormEvent. This event informs the FrontController, which instantiates a Command. The command executes the business logic, and the event is responsible for passing data to the command about the user interaction. The command can either take some action on the Model, or instantiate and act on a BusinessDelegate. The Business Delegate, or delegate for short, wraps the code required for a service call, so
it acts like the service API to the rest of the application. This is important because when the service changes, the changes to the application can be minimized and ideally only the delegate needs to
change. The delegate calls the service and then depending on the kind of service involved makes sure
that the command is informed when the service call has returned. Then the command changes the
state of the model, if necessary, and the model, through Flex’s binding, updates the view.

19.Explain the difference between creating an effect and setting the target as opposed to adding an effectListener
A: To create a behavior, you define a specific effect with a unique ID and bind it to the trigger.
For example, the following code creates two zoom effects: one for shrinking the component slightly,
and one for reverting it to its original size. These effects are assigned, by using their unique IDs, to
the mouseDownEffect and mouseUpEffect triggers on the Button component.
mx:Application ...>
mx:Zoom id="shrink" duration="100" zoomHeightTo=".9" zoomWidthTo=".9" />
mx:Zoom id="revert" duration="50" zoomHeightTo="1" zoomWidthTo="1" />
mx:Panel title="Bouncy Button" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" autoLayout="false" left="41" top="24" right="42">
mx:Button id="bouncyButton" label="Click me!" mouseDownEffect="{shrink}" mouseUpEffect="{revert}"/>
/mx:Panel>
/mx:Application>

20.How do you identify a component created in a repeater?
A: If currentIndex value is greater than startIndex value means a component is created in Repeater.
We can use count property to find number of children.
A Repeater component executes initially when it is instantiated. If the Repeater component's
dataProvider property exists, it proceeds to instantiate its children, and they instantiate their children, recursively. The Repeater component re-executes whenever itsdataProvider,startingIndex, orcount
properties are set or modified either explicitly in ActionScript, or implicitly by data binding.
When a Repeater component re-executes, it destroys any children that it previously created
(assuming therecycleChildren property is set tofalse), and then reinstantiates its children based
on the currentdataProvider property.

21.Differences between defining bindings in MXML and ActionScript?
A: There are a few differences between defining data bindings in MXML at compile time and in
defining them at runtime in ActionScript:
* You cannot include ActionScript code in a data binding expression defined by the bindProperty()
or bindSetter() method. Instead, use the bindSetter() method to specify a method to call when the
binding occurs.
* You cannot include an E4X expression in a data binding expression defined in ActionScript.
* You cannot include functions or array elements in property chains in a data binding expression
defined by the bindProperty() or bindSetter() method. For more information on property chains, see
Working with bindable property chains.
* The MXML compiler has better warning and error detection support than runtime data bindings defined by the bindProperty() or bindSetter() method.

Flex 1

 1. Is it possible to make httpService Requests synchronous?
A: No.
Solution : Basically, what we are about to do is creating XMLHttpRequest with Javascript in Flex,
and calling a server data with the parameters we will give to the object.
For example: xmlHttpRequest.open("GET","http://localhost/Default.aspx",false);
1. Request Type: GET or POST
2. Requested URL
3. Communication Type: true for asynchronous, false for synchronous.


2. I need to load an image from flickr into my application. Do I need a crossdomain.xml file on flickr?
A: File is already there , we need to register our ip address to flicker’s crossdomain.xml
? : Since the images are located on a flickr server like farm1.static.flickr.com and there is no
crossdomain.xml file on that server (there is a crossdomain.xml for api.flickr.com so you can use the
api) that means you can’t get access to the bitmapData of the loaded images when you load them
from flickr. This is dumb, but that’s the way it is. So you can load images just fine, but the reflection
class copies the bitmapData of the image, so that doesn’t work if you load them straight from the
flickr server. I also wanted to set bitmap smoothing to true on the images so the thumbnails don’t
look as pixelated, and that also requires access to the bitmapData of the loaded image.
So the answer is to create a proxy that loads the flickr image so it appears to come from the same domain.


3. What is the difference between httpService and Data Service?
A: The services-config.xml configuration file is required at compile time if the Flex application uses
Flex Data Services. In the case of RPC services, this applies to all applications that use
RemoteObject or proxy-based WebService or HTTPService.

4. How do you generate random numbers within a given limit with actionscript? A: Math.round(Math.random() * (high - low)) + low

5. Have you built any components with actionscript? If so explain how you did it? CountryComboBox.as package components { import mx.controls.ComboBox; public class CountryComboBox extends ComboBox
{ public function CountryComboBox()
{ dataProvider = [ "United States", "United Kingdom" ]; } } }

?xml version="1.0" encoding="utf-8"?>
mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:custom="components.*"
width="220" height="115">
custom:CountryComboBox />
/mx:Application>

6. How do you implement push on a flex applications?
A: Using BlazeDS Server, LiveCycle Data Services,



7.I am going to add images into a tag. How will it resize itself?
A1: To let Flex resize the image as part of laying out your application, set the height or width
properties to a percentage value. Flex attempts to resize components with percentage values for these
properties to the specified percentage of their parent container.
A2 : By default, Flex does not resize the image. The scaleContent property has a default value of
true, therefore, Flex scales the image as it resizes it to fit the specified height and width. The aspect
ratio is maintained by default, so the image may not completely fill the designated space. Set the
scaleContent property to false to disable scaling. Set the maintainAspectRatio property to false to
allow an image to fill all available space regardless of its dimensions.

8. What is a resource Manager??
A : the ResourceManager — now handles access to all localized resources in an application. Any
components that extend UIComponent, Formatter, or Validator now have a new resourceManager
property, which lets you easily access the singleton instance of this manager. If you’re writing some
other kind of class that needs to use the ResourceManager, you can call
ResourceManager.getInstance() to get a reference to it.

9.What are the similarities between java and flex?
A : Both can be used as client application, both have packages, OOP based , support XML , import
external packages, up casting, support ArrayCollection ,almost same primitive data types, both
support class library packaging( .jar , .swc).

10. What is the dynamic keyword used for?
A : Specifies that instances of a class may possess dynamic properties added at runtime. If you use
the dynamic attribute on a class, you can add properties to instances of that class at runtime. Classes
that are not marked as dynamic are considered sealed, which means that properties cannot be added
to instances of the class.

11.How do you implement push with flex data services? A : Using Blaze DS Server & LCDS 12. What are the methods called when a UI component is intialized?
A : all components dispatch the following events that let you specify ActionScript to initialize a
component:
preInitialize
Dispatched when a component has been created in a rough state, and no children have been created.
initialize
Dispatched when a component and all its children have been created, but before the component size
has been determined.
creationComplete
Dispatched when the component has been laid out and the component is visible (if appropriate).

13. How do you implement drag and drop on components that do not support ondrag and ondrop?

14.Can you write to the file system from flex? A: Yes . import flash.filesystem.*;
private var stream:FileStream;
private function saveFile():void{
var file:File = File.desktopDirectory.resolvePath("HelloWorld.txt");
var stream:FileStream = new FileStream()
stream.open(file, FileMode.WRITE);
var str:String = "Congratulations on your 1st file, Rich Tretola - EverythingFlex.com";
stream.writeUTFBytes(str);
stream.close();
mx.controls.Alert.show("File has been saved to \n" + file.nativePath, "Notice");

15. What is a drag manager?
A : The Flex Drag and Drop Manager lets you select an object, such as an item in a List control, or a
Flex control, such as an Image control, and then drag it over another component to add it to that
component.

16 . HOw do you call javascript from Flex?
A : Using the ExternalInterface API to access JavaScript from Flex and Using the navigateToURL()
method in Flex. The navigateToURL() method is in the flash.net package
flash.external.ExternalInterface.call(function_name:String[, arg1, ...]):Object;
navigateToURL(request:URLRequest, window:String):void

17. How do you use a repeater?
A:
mx:Application>
/mx:Script>
mx:Panel title="Repeater: emulating a for loop" paddingBottom="10" paddingLeft="10"
paddingRight="10" paddingTop="10">
mx:Repeater id="myRep" dataProvider="{myArray}">

/mx:Repeater>
/mx:Panel>
/mx:Application>

18. what are three ways to skin a component in flex?
A : Skinning is the process of changing the appearance of a component by modifying or replacing its visual elements. These elements can be made up of images, SWF files, or class files that contain drawing API methods. There are several ways that you can define skins: inline, by using the setStyle() method, and by using Cascading Style Sheets (CSS).

19.How do you use css styles in flex?
External styles are defined in a separate file and can be used in any MXML file that references the CSS file. You reference a CSS file into an MXML file with the source property of the mx:Style>ctag, as follows:
mx:Style source="../siteStyles.css"/>
Embedded styles are defined in an MXML file and can only be used in that file. Embedded styles are defined with the tag, as follows: mx:Style>
.myclass { background-color: xFF0000 }
TextInput { font-family: Helvetica; font-size: 12pt }
/mx:Style>
mx:Canvas>
mx:Button styleName="myclass">
/mx:Canvas>
Inline styles are defined in an MXML tag and can only be used in that tag. Inline styles are defined as follows:
mx:Button color="red"...>
mx:TextInput fontFamily="Helvetica" fontSize="12"...> 


20. What is the difference between sealed class and dynamic classes?
A : Classes are sealed by default, i.e. properties cannot be added dynamically at runtime.
* Dynamic classes can add additional dynamic properties at runtime; sealed classes cannot.
* Sealed classes conserve memory because no internal hash table is needed to store dynamic
properties, and the compiler can provide better error feedback.

Thursday, May 27, 2010

Silverlight 4

Question :: What features are missing from Silverlight presentation markup that will be supported in the Windows Presentation Foundation?
Ans::Microsoft recommends the Windows Presentation Foundation for building rich immersive applications and experiences that can take full advantage of the Windows platform, including UI, Media, offline communication, OS integration, Office integration, peripheral access, Document support and more. Silverlight will be used for broad reach interactive media content and browser-based rich interactive and high-performance applications and experiences.

Question :: When would a customer use Silverlight versus Windows Presentation Foundation? Is Silverlight for a certain type of application?
Ans::For ASP.NET-based Web applications, Silverlight provides a rich UI front-end that, with a consistent programming model, adds support for richer interactivity, media, and audio.
For Microsoft SharePoint–based content, Silverlight offers the ability to create rich Web parts. For Windows Live services, Silverlight offers the ability to consume services and APIs more effectively.

Question :: How does Silverlight make the Microsoft development system better?
Ans::Silverlight is a cross-browser, cross-platform plug-in for delivering the next generation of media experiences and rich interactive applications (RIAs) for the Web.

Question :: When would a customer use Silverlight instead of ASP.NET AJAX?
Ans::Silverlight integrates with existing Web applications, including ASP.NET AJAX applications. Consequently, ASP.NET AJAX and Silverlight are designed to be complementary technologies. In the broader sense, Silverlight can talk to any AJAX application, both client-side and server-side. ASP.NET AJAX can additionally be used to control Silverlight-based visualization of data or delivery of rich experiences. Examples might include mapping applications or video playback with rich presentation.

Question :: Are the features of the Macintosh and Windows releases of Silverlight fully compatible?
Ans::yes

Sunday, May 23, 2010

Silverlight 3

->Can SilverLight run in other platforms other than window?
Yes, animations made in SilverLight can run in other platforms other than window. In whatever platform you
want run you just need the SilverLight plug-in.

->What is the relationship between Silver Light, WPF and XAML?
XAML is a XML file which defines the UI elements. This XML file can be read by WPF framework or Silver light framework for rendering. Microsoft first developed WPF and they used XAML files to describe the UI elements to the WPF framework. Microsoft then extended WPF and made WPF/e which helped to render the UI in the browser. WPF/e was the code name for Silver Light. Later Microsoft launched Silver Light officially.
So the XAML just defines the XML structure to represent the UI elements. Both the frameworks i.e. WPF and Silverlight then reads the UI elements and renders the UI elements in the respective platform.

->Even WPF runs under browser why SilverLight?
Yes there is something called as WPF browser application which can run WPF in browser. For WPF browser application you need .Net framework to be installed in the client location while for silver light you need only the plug-in. So in other words WPF browser applications are OS dependent while SilverLight is not. SilverLight plug-in can run in other OS other than windows while we all know .NET framework only runs in windows.

->What is the difference between Silverlight 1 and Silverlight 2
Nothing, Silverlight 2 is a full superset of Silverlight 1.0 - it is 100% compatible with Silverlight 1.0 applications and provides significantly more powerful features and functionality. Silverlight 1.0 applications even benefit from improvements in media playback and performance characteristics of Silverlight 2 with no additional work.

->What kind of audio video formats are supported in Silverlight?
Silverlight supports Windows Media Audio and Video (WMA, WMV7-9) and VC-1, as well as MP3 audio.

->What is Silverlight Tool Kit?
To create an application or game you need to design, code and give some extra feature to your output.
To do the above, you need some controls, IDE etc.
Silverlight Tool kit is nothing but is a collection of Silverlight Tools, Components etc. It includes source code describing the all you need to develop an application.
The Silverlight Toolkit is a collection of Silverlight controls, components and utilities made available outside the normal Silverlight release cycle. A product of the Microsoft Silverlight product team, the Silverlight Toolkit adds new functionality quickly for designers and developers, and provides the community an efficient way to help shape product development by contributing ideas and bug reports. It includes full open source code, unit tests, samples and documentation for over 26 new controls covering charting, styling, layout, and user input.

->Can I add more than one .xaml pages in silverlight application?
Yes, you can have multiple .xaml files in a single project.In the App.xaml, in the method Application_Startup you can choose, which page you want to initially display.

Silverlight overview

Silver light has borrowed lot of things from existing Microsoft technologies. We can think silver light plug-in as a combination of some technologies from core .NET framework, vector animations, media and JavaScript.
 

So we can visualize the silver light architecture as combination of some functionalities from core .NET framework , Ajax and some functionalities like animation , media etc provided by core silver light framework.
We can think silver light architecture as a combination of four important blocks:-
• Some .NET framework components: - Silver light uses some components from .NET framework. One of the main components is WPF. Many of the UI components ( check box , buttons , text boxes etc) , XAML parsing etc are taken from the core WPF system. It also has taken components like WCF to simplify data access. It also have CLR for memory management, safety checking and garbage collection. The base class libraries of Net are used for string manipulations, algorithms, expressions, collections and globalization.
• Presentation core: - The core presentation framework has functionalities to display vector 2d animations, images, media, DRM and handle inputs like mouse and keyboard.
• Other technologies: - Silver light interacts with other technologies like Ajax and javascript. So it also borrows some functionalities from there technologies.
• Hosting: - Silver light animations finally run under the browser environment. So it has a the hosting functionality which helps to host the application the browser , expose a DOM by which JavaScript can manipulate the silver light components and it also has a installer functionality which helps to install silver light application and plug-in in the browser environment.
One of the things which you can notice from the architecture diagram is that the presentation core reads from the XAML file for rendering. The XAML is a component which is a part of the .NET framework and the rendering part is done by the presentation core.



The application is a typical HTML which runs under the browser. There are markups which instantiates the silver light plug-in. Now when user interacts with the silver light application it sends event to JavaScript system or the .NET system. This depends on which programming language you are using. The program code which is either in JavaScript of .NET can make calls to the silver light run-time and achieve the necessary functionalities. XAML will be read and parsed by the silver light runtime and then rendered accordingly to the browser.

Silverlight 2

->How to set Silverlight contents width as 100%?
Generally you can't set the UserControl width in % like 100% so that the Silverlight contents can spread in the
full screen.To get the 100% width of the screen you can set
width="auto" and height="auto".

->Can you provide a list of Layout Management Panels and when you will use them?
Canvas Panel:-use a canvas for simple layouts and when there is no need to resize panel. Controls can overlapped each other when resizing the panel.
Stack Panel:-use this for grouping controls in a stack (horizontal/vertical). Controls do not overlapped.
Grid Panel:-most flexible, multi row/columns layouts. Similar to a HTML table

->How can style elements be applied? (similar to a CSS file/skins)
Styles elements are supported in the form of application resources. An app.xaml file can be created containing an application resource Xml construct. The target type for each style is set to the control on which the style
needs to be applied.

App.xaml:
Application.Resource>
Style x:Key="MyBorder" TargetType="Border">
setter property="width" value="5">
/style>

Page.xaml:
Border Style="{StaticResource MyBorder}">
...
/Border>

->Can we add normal project reference (normal class library) to the Silverlight project?
No

->Is ADO.NET objects supported in Silverlight Project?
No, Silverlight project doesn't support normal ADO.NET objects like DataTable, DataSet, DataColumn, Database connection providers like SqlConnection, OledbConnection objects.
You can use System.Data namespace but that contains Services related stuffs not ADO.NET stuffs.

Silverlight 1

   
What is name of Linux version of silverlight ?
 LinLight

What is the difference between WPF and SilverLight?
SilverLight is a browser plugin for running it on web where WPF is used for window application. Though they both make use of XAML.

How to perform Event handling in silver light?.
Silverlight 1.0 uses JavaScript, while Silverlight 2.0 onwards uses C# (managed code) for event handling.

What are the Silverlight Event Mode?
In Silverlight, there are two event cases:
Input events
Non-input events.
Input Events: The browser that hosts the Silverlight plug-in handles initial input stimulus for the input events. This is because Silverlight works within the plug-in architecture of the hosting browser. From the browser, the event is sent to the Silverlight plug-in.
Then, it is raised as an event in the Silverlight Object Model.
Non-input Events: They report a state change to a particular object, for example, the state change events that report asynchronous download state or progress of actions initiated by Web Client. Some non-input events provide lifetime information of objects at a framework level.

For example the FrameworkElement.Loaded event
Some events, such as OnError, can only be handled by the Silverlight plug-in instance and exist within the HTML Document Object Model (DOM). These events need to be continually exposed and possibly handled by any script working with the plug-in instance in the DOM. Therefore; these events are not passed to the managed programming model.

Can we add the reference of a Class library project in Silverlight application project?
No, You can't add the reference of a Class library inside the Silverlight application project. You can only add the reference of another Silverlight application project inside a Silverlight application project.
However, you can add the reference of a Web Service or WCF services.

What is Silverlight.js file?
Silverlight.js is a helper file which enables Web sites to create advanced Silverlight installation and instantiation experiences.

What does XAP mean?
XAP (pronounced ZAP) is the file extension for a Silverlight-based application package (.xap). This file contains the compressed assemblies and resources of a Silverlight  application.

What is a .xap file?
A .xap file is a Silverlight-based application package (.xap) that is generated when the Silverlight project is built.

How does XAP work?
Once you have created the .xap file, the Silverlight  plug-in downloads the file and runs it in a separate work space.

How do I use a .xap file?
A .xap file is used to contain and transfer the assemblies and resources of a managed code application. This managed code application must be run within the Silverlight  browser plug-in.

How can I view the contents of a .xap file?
To view the contents of a .xap file you can rename the extension of the .xap file to .zip. Then view the .zip file using any standard .zip utility.

What are the files contained in the .xap file?
A basic xap file will have an assembly related to specific code for the application, an application manifest file and any additional assemblies need to run the application. At a minimum, two files are needed, the application manifest file and the application assembly.
For example:
AppManifest.xaml
MyPianoV2.dll

What is contained in the AppManifest.xaml file?
The AppManifest.xaml file contains the deployment details needed to run the application.
The AppManifest.xaml file defines the assemblies that get deployed in the client application. This file is automatically updated when compiling your application. Based on the settings of a referenced assembly it is added to the Application manifest. For example, if you have an assembly that you are referencing in your application but do not wish to have it included into the. XAP file you can choose to set “Copy Local” to false.

Basic example:

                 Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="MyPianoV2" EntryPointType="MyPianoV2.App" RuntimeVersion="2.0.30523.4"
  Deployment.Parts   
AssemblyPart x:Name="MyPianoV2" Source="MyPianoV2.dll" /  
/Deployment.Parts
/Deployment

.XAP generation tool:
When you use the Silverlight project template in Visual Studio 2008 the .XAP file gets generated automatically for you. This is done in a post-build action that uses a tool called Chiron; a tool that gets installed with the Silverlight .
The Chiron tool can also be accessed via the command line to package your own .XAP files if needed. You can also use this tool to generate the .XAP for a DLR application.

What are the requirements to display the contents of the .xap file when I run the application in a Web page within the browser?
·         Make sure you are using the Silverlight  plug-in.
·         Make sure you have the XAP mime type set for IIS .
·         Make sure you included your resources, such as graphics, with your Silverlight Application
·         Make sure the .xap file is contained in the ClientBin folder of your Web application.

What is the XAP mime type?
The .xap mime type is:
application/x-silverlight
 

How do I run the Silverlight application (including the .xap file) with the Silverlight  plug-in?
You can use the ASP.NET Silverlight Server Control to reference your .xap file. Specifically, you use the Source property to reference the XAP application package. The Version must be set as well.

What is the XmlXapResolver class?
The XmlXapResolver class is used to resolve resources that are contained in the Silverlight application’s XAP package.

What is the use of ClientBin folder?
ClientBin folder is used to place the .xap file of Silverlight application. You can keep this anywhere in your web application but this is the default that is used by the Silverlight.

What is the parent xaml tag of Silverlight page?
UserControl is the parent xaml tag of the Silverlight page. All other tags are placed under UserControl tag.

UserControl x:Class="SilverlightApplication2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300";

Grid x:Name="LayoutRoot" Background="White"
/Grid
/UserControl
   

How to change the default page of the Silverlight application?
To change the default page of Silverlight application, you need to set the RootVisual property inside the Application_Startup even of App.xaml file.

private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new YourPage();
        }

When you create a new project in Silverlight through Visual Studio, how many xaml files are created and what are the uses of those files?
When we create a Silverlight application from Visual Studio, two (2) xaml files are created into the Silverlight project.
They are:
1. App.xaml - App.xaml is a file used to declare shared resources like brushes, various style objects etc. and to handle the global application level event (this is almost similar to global.asax file in asp.net application). By default following events are created in the App.xaml.cs file.
Application_Startup
Application_Exit
Application_UnhandledException
ReportErrorToDOM

2. MainPage.xaml or Page.xaml - This page is the default page of the Silverlight application and when the silverlight application runs this becomes the default page to appear (this page is like the default.aspx page of asp.net application)

Which programming language can be used to write the backend of the Silverlight application?
We can either use C# or Visual Basic to code the backend of the silverlight application. Here backend means the code behind files for the Sivlerlight pages.

Which language is used to design the layout in Silverlight?
XAML language is used.
Extensible Application Markup Language (XAML, pronounced zammel ) is a declarative XML-based language created by Microsoft which is used as a user interface markup language to define UI elements, data binding, eventing, and other features.

Saturday, May 15, 2010

WCF 3

1. A user has a service with a one-way operation that includes a fault contract, and he
gets an exception when he tries to host the service. Why?
    This happens because, to return faults, the service needs some form of a two-way communication channel in place, which is not the case with one-way operations.

2. A user has a service he wants to expose on the Internet, and it needs to send notifications
out to its consumers. Would the WCF Duplex MEP be a good choice for implementing this?
    No. The WCF Duplex MEP can be problematic to enable, even inside an enterprise.
Its implementation depends upon the service establishing a connection back to the consumer, which can’t happen in certain scenarios, such as when the client’s machine uses NAT behind a firewall. On the Internet, where you are never certain
where your consumers are coming from, this type of callback channel would rarely, if ever, work. When you factor in the security risks it could pose and the scalability concerns with the fact that callback channels require the presence of sessions
between client and service, it isn’t a feasible solution.


3. You have a Data contract specifying a Person class from which you derive a Customer class. Does a Customer object automatically have a Data contract as well?
    No. The Data contract is not inherited, so any derived class, such as the Customer class, would have to be explicitly declared as having a Data contract as well.


4. Your company has its own proprietary authentication mechanism, and you are required to authenticate every message coming into the service. What is the best way to handle using this mechanism with WCF?
    Likely the best way to handle this would be to design a Message contract that accepts these proprietary authentication tokens in the header.

5. Can you support the Rpc SOAP style by using the DataContractSerializer?
    Yes. You need only adorn your service with the DataContractFormatAttribute and explicitly set the attribute’s Style property to OperationFormatStyle.Rpc.

6. What does the “ABCs of endpoints” refer to?
    The ABCs of endpoints refers to the three required elements that comprise a service endpoint: address, binding, and contract.

7. Which standard binding could be used for a service that was designed to replace an existing ASMX Web service?
    The basicHttpBinding standard binding was designed to expose a service as if it were an ASMX Web service. This enables you to support existing clients as applications are upgraded to WCF.

8. What is the main disadvantage of using IIS to host a service?
    Using IIS to host your services means that you will not be able to support non-HTTP protocols such as TCP, named pipes, and MSMQ. You will have access to the many built-in features available with IIS such as process recycling and messagebased
activation.

9. Which file specifies the types that your service will expose in IIS?
    Service types are exposed through IIS by using the service file. This file must have an .svc file extension and should reside in the application directory for your IIS hosting application. This file will include an @ServiceHost directive, which specifies
the service name and language for the service code files. These files should be located in an App_Code subdirectory.

10.What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.

11. What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF 2

How to set the timeout property for the WCF Service client call?

The timeout property can be set for the WCF Service client call using binding tag.

      ...

      binding = "wsHttpBinding"

      bindingConfiguration = "LongTimeout"

      ...

   />


If no timeout has been specified, the default is considered as 1 minute.

How to configure Reliability while communicating with WCF Services?

Reliability can be configured in the client config file by adding reliableSession under binding tag.
          

            address  = "net.tcp://localhost:8888/MyService"

            binding  = "netTcpBinding"

            bindingConfiguration = "ReliableCommunication"

            contract = "IMyContract"

         />

    
Reliability is supported by following bindings only


NetTcpBinding

WSHttpBinding

WSFederationHttpBinding

WSDualHttpBinding

What is Transport and Message Reliability?

Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.


Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.

What are different elements of WCF Srevices Client configuration file?

WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like
     

         address  = "http://localhost:8000/MyService/"

         binding  = "wsHttpBinding"

         contract = "IMyContract"

      />

  

What is Proxy and how to generate proxy for WCF Services?

The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.


The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.


Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.


SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs


When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:


SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
What are contracts in WCF?

In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.


WCF defines four types of contracts.



Service contracts


Describe which operations the client can perform on the service.

There are two types of Service Contracts.

ServiceContract - This attribute is used to define the Interface.

OperationContract - This attribute is used to define the method inside Interface.


[ServiceContract]

interface IMyContract

{

   [OperationContract]

   string MyMethod( );

}

class MyService : IMyContract

{

   public string MyMethod( )

   {

      return "Hello World";

   }

}




Data contracts


Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.


There are two types of Data Contracts.

DataContract - attribute used to define the class

DataMember - attribute used to define the properties.


[DataContract]

class Contact

{

   [DataMember]

   public string FirstName;



   [DataMember]

   public string LastName;

}



If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.


Fault contracts


Define which errors are raised by the service, and how the service handles and propagates errors to its clients.



Message contracts


Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.
What is the address formats of the WCF transport schemas?

Address format of WCF transport schema always follow


[transport]://[machine or domain][:optional port] format.


for example:


HTTP Address Format


http://localhost:8888

the way to read the above url is


"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"

When the port number is not specified, the default port is 80.


TCP Address Format


net.tcp://localhost:8888/MyService


When a port number is not specified, the default port is 808:


net.tcp://localhost/MyService


NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.


IPC Address Format

net.pipe://localhost/MyPipe


We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.


MSMQ Address Format

net.msmq://localhost/private/MyService

net.msmq://localhost/MyService
How to define a service as REST based service in WCF?

WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

The below code shows how to expose a RESTful service


[ServiceContract]

interface IStock

{

[OperationContract]

[WebGet]

int GetStock(string StockId);

}



By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.
What is endpoint in WCF?

Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.


The Endpoint is the fusion of Address, Contract and Binding.
What is binding and how many types of bindings are there in WCF?

A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.


WCF supports nine types of bindings.


Basic binding


Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.


TCP binding


Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.



Peer network binding


Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.



IPC binding


Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.



Web Service (WS) binding


Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.



Federated WS binding


Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.



Duplex WS binding


Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.



MSMQ binding


Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.



MSMQ integration binding

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are
1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)

What is address in WCF and how many types of transport schemas are there in WCF?

Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.


WCF supports following transport schemas


HTTP

TCP

Peer network

IPC (Inter-Process Communication over named pipes)

MSMQ


The sample address for above transport schema may look like


http://localhost:81

http://localhost:81/MyService

net.tcp://localhost:82/MyService

net.pipe://localhost/MyPipeService

net.msmq://localhost/private/MyMsMqService

net.msmq://localhost/MyMsMqService