Actionscript compiler MTASC and Events - actionscript

Please help, how to make netEvent work in a compiled flash, for instance I can't even make macromedia example to work:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.onMetaData = function(infoObject:Object) {
for (var propName:String in infoObject) {
trace(propName + " = " + infoObject[propName]);
}
};
ns.play("http://www.helpexamples.com/flash/video/water.flv");
It must return metainfo, but seems like no event is called at all.
What am I doing wrong?
Thanks!

This is right from Adobe docs:
package {
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.Event;
public class NetConnectionExample extends Sprite {
private var videoURL:String = "Video.flv";
private var connection:NetConnection;
private var stream:NetStream;
public function NetConnectionExample() {
connection = new NetConnection();
connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
connection.connect(null);
}
private function netStatusHandler(event:NetStatusEvent):void {
switch (event.info.code) {
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Stream not found: " + videoURL);
break;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function connectStream():void {
stream = new NetStream(connection);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.client = new CustomClient();
var video:Video = new Video();
video.attachNetStream(stream);
stream.play(videoURL);
addChild(video);
}
}
}
class CustomClient {
public function onMetaData(info:Object):void {
trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
}
public function onCuePoint(info:Object):void {
trace("cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type);
}
}
Looks to me like you're missing quite a bit in the code that you posted and you won't get what you're looking for by missing required setup code.

Related

how to display a WebView only after a javascript code is done?

I'm trying to force WebView to 'skip' images by using javascript. (like here: https://stackoverflow.com/a/31848599/13174607).
The problem is that the images are disappeared only after the WebView finished loaded. I want to display the WebView only after the javascript is finished.
This is my code:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webView, url);
webView.loadUrl("javascript:(function(){ var imgs=document.getElementsByTagName('img');" + "for(i=0;i<imgs.length;i++) { imgs[i].style.display='none'; } })()");
}
});
}
I tried to use setVisibility() method, like this:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
webView.setVisibility(View.INVISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webView, url);
webView.loadUrl("javascript:(function(){ var imgs=document.getElementsByTagName('img');" + "for(i=0;i<imgs.length;i++) { imgs[i].style.display='none'; } })()");
webView.setVisibility(View.VISIBLE);
}
});
}
but it didn't help.
Thanks!
EDIT:
By using the proposed solution and the #mustansir comments I wrote this code on 'onPageFinished':
webView.loadUrl("javascript:" + "function taskOne() {" +
"var imgFlag = 0;" + //will sign when the for loop ended
"var imgs = document.getElementsByTagName('img');" +
"if (imgs==0){imgFlag=1;} " +
"for (i = 0; i < imgs.length; i++) {" +
"imgs[i].style.display = 'none';" +
"if (i==imgs.length-1)" +
"{" +
"imgFlag=1;" +
"}"+
"}}" +
"taskOne();" +
"function taskTwo () {" +
"if(imgFlag==1){" +
"window.visibility.changeVisibility(); }" +
"else {" +
"setTimeout(taskTwo(),100);}}" +
"taskTwo();");
but the the webview doesn't become visible. Any idea why?
You can try injecting a JavaScript interface and call that interface method when you reach at the last image in the loop to change WebView visibility.
Something like this:
webview.addJavascriptInterface(this, "visibility");
and call this interface from your JavaScript like this:
var imgs = document.getElementsByTagName('img');
for (i = 0; i < imgs.length; i++) {
imgs[i].style.display = 'none';
if (i == imgs.length-1) {
visibility.changeVisibility();
}
}
Now define changeVisibility() with #JavascriptInterface annotation in that activity in which you have added javascriptInterface like this:
#JavascriptInterface
public void changeVisibility() {
runOnUiThread(() -> webview.setVisibility(View.VISIBLE));
}

GPS.ane for my app and i keep getting an error Line 55, Column 50 1120: Access of undefined property onClickStop

**trying to use the GPS.ane for my app and I keep getting an error
"Line 55, Column 50 1120: Access of undefined property onClickStop."
this is the line that is giving me the headache I think I am missing something small but i cant find it. The app is as you will think gives out the latitude and longitude of where you are at. thank you for you help **
**package {
import com.myflashlab.air.extensions.gps.Gps;
import com.myflashlab.air.extensions.gps.LocationAccuracy;
import com.myflashlab.air.extensions.gps.Location;
import com.myflashlab.air.extensions.gps.GpsEvent;
import com.myflashlab.air.extensions.nativePermissions.PermissionCheck;
import flash.utils.setTimeout;
import com.myflashlab.air.extensions.dependency.OverrideAir;
import flash.desktop.NativeApplication;
import flash.desktop.SystemIdleMode;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.StatusEvent;
import flash.events.InvokeEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.filesystem.File;
import flash.text.AntiAliasType;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.ui.Keyboard;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Main extends MovieClip{
private var _exPermissions:PermissionCheck = new PermissionCheck();
public function Main() {
// constructor code
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, handleActivate);
NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, handleDeactivate);
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleKeys);
stage.scaleMode = StageScaleMode.EXACT_FIT;
stage.align = StageAlign.TOP_LEFT;
startBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStart);
stopBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStop);
checkPermissions();
}
private function onInvoke(e:InvokeEvent):void
{
NativeApplication.nativeApplication.removeEventListener(InvokeEvent.INVOKE, onInvoke);
}
private function handleActivate(e:Event):void
{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
}
private function handleDeactivate(e:Event):void
{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.NORMAL;
}
private function handleKeys(e:KeyboardEvent):void
{
if(e.keyCode == Keyboard.BACK)
{
e.preventDefault();
NativeApplication.nativeApplication.exit();
}
}
private function checkPermissions():void
{
// first you need to make sure you have access to the Location API
var permissionState:int;
if(_exPermissions.os == PermissionCheck.ANDROID)
{
permissionState = _exPermissions.check(PermissionCheck.SOURCE_LOCATION);
}
else if(_exPermissions.os == PermissionCheck.IOS)
{
permissionState = _exPermissions.check(PermissionCheck.SOURCE_LOCATION_WHEN_IN_USE);
}
if (permissionState == PermissionCheck.PERMISSION_UNKNOWN || permissionState == PermissionCheck.PERMISSION_DENIED)
{
if(_exPermissions.os == PermissionCheck.ANDROID)
{
_exPermissions.request(PermissionCheck.SOURCE_LOCATION, onRequestResult);
}
else if(_exPermissions.os == PermissionCheck.IOS)
{
_exPermissions.request(PermissionCheck.SOURCE_LOCATION_WHEN_IN_USE, onRequestResult);
}
}
else
{
textDisplay.appendText("permissions are already ok, you can use gps features."+ "\n");
init();
}
function onRequestResult($state:int):void
{
if ($state != PermissionCheck.PERMISSION_GRANTED)
{
textDisplay.appendText("You did not allow the app the required permissions!"+ "\n");
}
else
{
textDisplay.appendText("necessary permissions are now granted."+ "\n");
init();
}
}
}
public function onClickStart (evt:TouchEvent):void{
textDisplay.appendText("Location Uptade Started.\n");
// use the start method to get gps information periodically (the gps icon will be shown at your device status bar)
Gps.location.addEventListener(GpsEvent.LOCATION_UPDATE, onLocationUpdate);
Gps.location.start(LocationAccuracy.HIGH, 0, 5000);
startBtn.alpha = 0.5;
stopBtn.alpha = 1;
}
public function onClickstop (evt:TouchEvent):void{
textDisplay.appendText("Location Uptade Stopped.\n");
// simply stop the gps service when you don't need to get location information periodically anymore.
Gps.location.removeEventListener(GpsEvent.LOCATION_UPDATE, onLocationUpdate);
Gps.location.stop();
startBtn.alpha = 1;
stopBtn.alpha = 0.5;
}
function onLocationUpdate(e:GpsEvent):void
{
textDisplay.appendText(" ------------------------------- onLocationUpdate"+ "\n");
var loc:Location = e.param;
textDisplay.appendText("accuracy = " + loc.accuracy+ "\n");
textDisplay.appendText("altitude = " + loc.altitude+ "\n");
textDisplay.appendText("bearing = " + loc.bearing+ "\n");
textDisplay.appendText("latitude = " + loc.latitude+ "\n");
textDisplay.appendText("longitude = " + loc.longitude+ "\n");
textDisplay.appendText("provider = " + loc.provider+ "\n");
textDisplay.appendText("speed = " + loc.speed+ "\n");
textDisplay.appendText("time = " + loc.time+ "\n");
textDisplay.appendText("---------------------------------"+ "\n");
}
private function myDebuggerDelegate($ane:String, $class:String, $msg:String):void
{
textDisplay.appendText($ane+"("+$class+") "+$msg+ "\n");
}
private function init():void
{
// remove this line in production build or pass null as the delegate
OverrideAir.enableDebugger(myDebuggerDelegate);
Gps.init(); // call init only once in your project
// will return null if no known last location has been found
Gps.location.getLastLocation(onLocationResult);
// may take a while depending on when gps info is found
Gps.location.getCurrentLocation(onLocationResult);
function onLocationResult($result:Location):void
{
if (!$result)
{
textDisplay.appendText("location is null"+ "\n");
return;
}
textDisplay.appendText("accuracy = " + $result.accuracy+ "\n");
textDisplay.appendText("altitude = " + $result.altitude+ "\n");
textDisplay.appendText("bearing = " + $result.bearing+ "\n");
textDisplay.appendText("latitude = " + $result.latitude+ "\n");
textDisplay.appendText("longitude = " + $result.longitude+ "\n");
textDisplay.appendText("provider = " + $result.provider+ "\n");
textDisplay.appendText("speed = " + $result.speed+ "\n");
textDisplay.appendText("time = " + $result.time+ "\n");
textDisplay.appendText("---------------------------------"+ "\n");
}
}
}
}
**
stopBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStop);
public function onClickstop (evt:TouchEvent):void{
Your function has a low case s in stop, but when you refer to it you use a capital S.
Think that's all that's wrong

ActionScript, NetStream.Play.Failed iOS AIR mobile

I'm trying to stream local audio files in m4a (aac) similar to Tiberiu-Ionuț Stan (http://stackoverflow.com/questions/2036107/aac-mp4-not-working-in-actionscript-3s-netstream):
package
{
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.NetStatusEvent;
import flash.events.AsyncErrorEvent;
import flash.events.Event;
public class Mysound
{
private var _connection:NetConnection;
private var _netStream:NetStream;
private var _filePath:String;
private var _client:Object;
public function MainDocument(filePath:String):void
{
_filePath = filePath;
connect();
}
private function connect():void
{
_connection=new NetConnection();
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
_connection.connect(null);
}
private function netStatusHandler(event:NetStatusEvent):void
{
switch (event.info.code)
{
case "NetConnection.Connect.Success":
requestAudio();
break;
}
}
private function requestAudio():void
{
_netStream=new NetStream(_connection);
_netStream.addEventListener(NetStatusEvent.NET_STATUS, this._netStatusHandler);
_netStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, this._asyncErrorHandler);
_client = new Object();
_client.onMetaData = onMetaData;
_netStream.client = _client;
_netStream.backBufferTime = 0;
_netStream.bufferTime = 0.5;
_netStream.bufferTimeMax = 5;
_netStream.play(filePath);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace(event);
}
private function onMetaData(metadata:Object):void
{
var str:String = "";
for (var key:String in metadata) {
str += key + ": " + metadata[key];
}
trace(str);
}
}
}
It works for me on emulator but it doesn't on devices (ipads).
I found out that netStatusHandler on device catches status "NetStream.Play.Failed", but i have no idea why, I know that it correctly reads file as it does get correct metadata, it also starts to buffer sound, but fails to play it. Files are in folder next to my app swf so it shouln't be sandbox problem. What else should I try to get it working?

Moving a work item between projects in TFS

Is it possible to move a work item from one project to another inside TFS? I’ve seen a copy option, but no move. Also, if it is possible, what’s the implication for any of the WI history?
I found this article from 2008 that seem to say it's not, but I wondered if there'd been any progress since then.
It isn't possible to move, just copy. The way we do it, is we do the copy, link the original, then close the original as obsolete. You could also create the copy and TF Destroy the original, but you will lose all history.
If you wanted to, you could get very fancy and create your own "move" utility that copies the workitem and all of the history, then closes out (or destroys) the old one. Seems like overkill for something that you probably shouldn't need to do all that often.
Lars Wilhelmsen wrote a WorkItemMigrator -> http://larsw.codeplex.com/SourceControl/list/changesets
Good starting point for a utility you can customize for your needs. We used it to split off a 100 or so work items to a new project. Here's the program I ended up with. Modify the query to subset the items to migrate.
namespace WorkItemMigrator
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
class Program
{
#region Members
private static readonly Dictionary<Uri, TfsTeamProjectCollection> Collections = new Dictionary<Uri, TfsTeamProjectCollection>();
private static readonly Uri SourceCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
private static readonly Uri TargetCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
private const String Areas = "ProjectModelHierarchy";
private const string Iterations = "ProjectLifecycle";
private const string TargetProjectName = "TargetProject";
private const string MicrosoftVstsCommonStackRankFieldName = "Microsoft.VSTS.Common.StackRank";
private const string MicrosoftVstsCommonPriority = "Microsoft.VSTS.Common.Priority";
private const string TargetWorkItemType = "User Story";
private const string Wiql = "SELECT [System.Id], [System.State], [System.Title], [System.AssignedTo], [System.WorkItemType], [Microsoft.VSTS.Common.Priority], " +
"[System.IterationPath], [System.AreaPath], [System.History], [System.Description] " +
"FROM WorkItems WHERE [System.TeamProject] = 'SourceProject' AND " +
"[System.State] = 'Active' " +
"ORDER BY [System.Id]";
private static WorkItemTypeCollection WorkItemTypes;
private static Dictionary<int, int> WorkItemIdMap = new Dictionary<int, int>();
#endregion
static void Main()
{
var createAreasAndIterations = GetRunMode();
var sourceWorkItemStore = GetSourceWorkItemStore();
var sourceWorkItems = sourceWorkItemStore.Query(Wiql);
var targetWorkItemStore = GetTargetWorkItemStore();
var targetProject = targetWorkItemStore.Projects[TargetProjectName];
WorkItemTypes = targetProject.WorkItemTypes;
foreach (WorkItem sourceWorkItem in sourceWorkItems)
{
if (createAreasAndIterations)
{
Console.WriteLine();
EnsureThatStructureExists(TargetProjectName, Areas, sourceWorkItem.AreaPath.Substring(sourceWorkItem.AreaPath.IndexOf("\\") + 1));
EnsureThatStructureExists(TargetProjectName, Iterations, sourceWorkItem.IterationPath.Substring(sourceWorkItem.IterationPath.IndexOf("\\") + 1));
}
else
{
MigrateWorkItem(sourceWorkItem);
}
}
if (!createAreasAndIterations)
{
var query = from WorkItem wi in sourceWorkItems where wi.Links.Count > 0 select wi;
foreach (WorkItem sourceWorkItem in query)
{
LinkRelatedItems(targetWorkItemStore, sourceWorkItem);
}
}
TextWriter tw = File.CreateText(#"C:\temp\TFS_MigratedItems.csv");
tw.WriteLine("SourceId,TargetId");
foreach (var entry in WorkItemIdMap)
{
tw.WriteLine(entry.Key + "," + entry.Value);
}
tw.Close();
Console.WriteLine();
Console.WriteLine("Done! Have a nice day.");
Console.ReadLine();
}
private static bool GetRunMode()
{
bool createAreasAndIterations;
while (true)
{
Console.Write("Create [A]reas/Iterations or [M]igrate (Ctrl-C to quit)?: ");
var command = Console.ReadLine().ToUpper().Trim();
if (command == "A")
{
createAreasAndIterations = true;
break;
}
if (command == "M")
{
createAreasAndIterations = false;
break;
}
Console.WriteLine("Unknown command " + command + " - try again.");
}
return createAreasAndIterations;
}
private static void MigrateWorkItem(WorkItem sourceWorkItem)
{
var targetWIT = WorkItemTypes[sourceWorkItem.Type.Name];
var newWorkItem = targetWIT.NewWorkItem();
//var newWorkItem = targetWorkItemType.NewWorkItem();
// Description (Task) / Steps to reproduce (Bug)
if (sourceWorkItem.Type.Name != "Bug")
{
newWorkItem.Description = sourceWorkItem.Description;
}
else
{
newWorkItem.Fields["Microsoft.VSTS.TCM.ReproSteps"].Value = sourceWorkItem.Description;
}
// History
newWorkItem.History = sourceWorkItem.History;
// Title
newWorkItem.Title = sourceWorkItem.Title;
// Assigned To
newWorkItem.Fields[CoreField.AssignedTo].Value = sourceWorkItem.Fields[CoreField.AssignedTo].Value;
// Stack Rank - Priority
newWorkItem.Fields[MicrosoftVstsCommonPriority].Value = sourceWorkItem.Fields[MicrosoftVstsCommonPriority].Value;
// Area Path
newWorkItem.AreaPath = FormatPath(TargetProjectName, sourceWorkItem.AreaPath);
// Iteration Path
newWorkItem.IterationPath = FormatPath(TargetProjectName, sourceWorkItem.IterationPath);
// Activity
if (sourceWorkItem.Type.Name == "Task")
{
newWorkItem.Fields["Microsoft.VSTS.Common.Activity"].Value = sourceWorkItem.Fields["Microsoft.VSTS.Common.Discipline"].Value;
}
// State
//newWorkItem.State = sourceWorkItem.State;
// Reason
//newWorkItem.Reason = sourceWorkItem.Reason;
// build a usable rendition of prior revision history
RevisionCollection revisions = sourceWorkItem.Revisions;
var query = from Revision r in revisions orderby r.Fields["Changed Date"].Value descending select r;
StringBuilder sb = new StringBuilder(String.Format("Migrated from work item {0}<BR />\n", sourceWorkItem.Id));
foreach (Revision revision in query)
{
String history = (String)revision.Fields["History"].Value;
if (!String.IsNullOrEmpty(history))
{
foreach (Field f in revision.Fields)
{
if (!Object.Equals(f.Value, f.OriginalValue))
{
if (f.Name == "History")
{
string notation = string.Empty;
if (revision.Fields["State"].OriginalValue != revision.Fields["State"].Value)
{
notation = String.Format("({0} to {1})", revision.Fields["State"].OriginalValue, revision.Fields["State"].Value);
}
//Console.WriteLine("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation);
sb.Append(String.Format("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}<BR />\n", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation));
}
}
}
//Console.WriteLine("Revision {0}: ", revision.Fields["Rev"].Value);
//Console.WriteLine(" ChangedDate: " + revision.Fields["ChangedDate"].Value);
//Console.WriteLine(" History: " + sb.ToString());
}
}
newWorkItem.History = sb.ToString();
// Attachments
for (var i = 0; i < sourceWorkItem.AttachedFileCount; i++)
{
CopyAttachment(sourceWorkItem.Attachments[i], newWorkItem);
}
// Validate before save
if (!newWorkItem.IsValid())
{
var reasons = newWorkItem.Validate();
Console.WriteLine(string.Format("Could not validate new work item (old id: {0}).", sourceWorkItem.Id));
foreach (Field reason in reasons)
{
Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
}
}
else
{
Console.Write("[" + sourceWorkItem.Id + "] " + newWorkItem.Title);
try
{
newWorkItem.Save(SaveFlags.None);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(string.Format(" [saved: {0}]", newWorkItem.Id));
WorkItemIdMap.Add(sourceWorkItem.Id, newWorkItem.Id);
Console.ResetColor();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
private static void CopyAttachment(Attachment attachment, WorkItem newWorkItem)
{
using (var client = new WebClient())
{
client.UseDefaultCredentials = true;
client.DownloadFile(attachment.Uri, attachment.Name);
var newAttachment = new Attachment(attachment.Name, attachment.Comment);
newWorkItem.Attachments.Add(newAttachment);
}
}
private static void LinkRelatedItems(WorkItemStore targetWorkItemStore, WorkItem sourceWorkItem)
{
int newId = WorkItemIdMap[sourceWorkItem.Id];
WorkItem targetItem = targetWorkItemStore.GetWorkItem(newId);
foreach (Link l in sourceWorkItem.Links)
{
if (l is RelatedLink)
{
RelatedLink sl = l as RelatedLink;
switch (sl.ArtifactLinkType.Name)
{
case "Related Workitem":
{
if (WorkItemIdMap.ContainsKey(sl.RelatedWorkItemId))
{
int RelatedWorkItemId = WorkItemIdMap[sl.RelatedWorkItemId];
RelatedLink rl = new RelatedLink(sl.LinkTypeEnd, RelatedWorkItemId);
// !!!!
// this does not work - need to check the existing links to see if one exists already for the linked workitem.
// using contains expects the same object and that's not what I'm doing here!!!!!!
//if (!targetItem.Links.Contains(rl))
// !!!!
var query = from RelatedLink qrl in targetItem.Links where qrl.RelatedWorkItemId == RelatedWorkItemId select qrl;
if (query.Count() == 0)
{
targetItem.Links.Add(rl); ;
// Validate before save
if (!targetItem.IsValid())
{
var reasons = targetItem.Validate();
Console.WriteLine(string.Format("Could not validate work item (old id: {0}) related link id {1}.", sourceWorkItem.Id, sl.RelatedWorkItemId));
foreach (Field reason in reasons)
{
Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
}
}
else
{
try
{
targetItem.Save(SaveFlags.None);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(string.Format(" [Updated: {0}]", targetItem.Id));
Console.ResetColor();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
break;
}
default:
{ break; }
}
}
}
}
private static void EnsureThatStructureExists(string projectName, string structureType, string structurePath)
{
var parts = structurePath.Split('\\');
var css = GetCommonStructureService();
var projectInfo = css.GetProjectFromName(projectName);
var parentNodeUri = GetCssStructure(GetCommonStructureService(), projectInfo.Uri, structureType).Uri;
var currentPath = FormatPath(projectName, structureType == Areas ? "Area" : "Iteration");
foreach (var part in parts)
{
currentPath = FormatPath(currentPath, part);
Console.Write(currentPath);
try
{
var currentNode = css.GetNodeFromPath(currentPath);
parentNodeUri = currentNode.Uri;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine(" [found]");
}
catch
{
parentNodeUri = css.CreateNode(part, parentNodeUri);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" [created]");
}
Console.ResetColor();
}
}
private static string FormatPath(string currentPath, string part)
{
part = part.Substring(part.IndexOf("\\") + 1);
currentPath = string.Format(#"{0}\{1}", currentPath, part);
return currentPath;
}
private static TfsTeamProjectCollection GetProjectCollection(Uri uri)
{
TfsTeamProjectCollection collection;
if (!Collections.TryGetValue(uri, out collection))
{
collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
collection.Connect(ConnectOptions.IncludeServices);
collection.Authenticate();
Collections.Add(uri, collection);
}
return Collections[uri];
}
private static WorkItemStore GetSourceWorkItemStore()
{
var collection = GetProjectCollection(SourceCollectionUri);
return collection.GetService<WorkItemStore>();
}
private static WorkItemStore GetTargetWorkItemStore()
{
var collection = GetProjectCollection(TargetCollectionUri);
return collection.GetService<WorkItemStore>();
}
public static NodeInfo GetCssStructure(ICommonStructureService css, String projectUri, String structureType)
{
return css.ListStructures(projectUri).FirstOrDefault(node => node.StructureType == structureType);
}
private static ICommonStructureService GetCommonStructureService()
{
var collection = GetProjectCollection(TargetCollectionUri);
return collection.GetService<ICommonStructureService>();
}
}
}

Adobe Air how to check if URL is online\gives any response exists?

I have url I want to check if it is live. I want to get bool value. How to do such thing?
You can use an URLLoader and listen for the events to check if it loads, and if not what might be the problem. Would be handy to use the AIRMonitor first to make sure the client's computer is online in the first place.
Here is a class I started to write to illustrate the idea:
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
/**
* ...
* #author George Profenza
*/
public class URLChecker extends EventDispatcher
{
private var _url:String;
private var _request:URLRequest;
private var _loader:URLLoader;
private var _isLive:Boolean;
private var _liveStatuses:Array;
private var _completeEvent:Event;
private var _dispatched:Boolean;
private var _log:String = '';
public function URLChecker(target:IEventDispatcher = null)
{
super(target);
init();
}
private function init():void
{
_loader = new URLLoader();
_loader.addEventListener(Event.COMPLETE, _completeHandler);
_loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, _httpStatusHandler);
_loader.addEventListener(IOErrorEvent.IO_ERROR, _ioErrorEventHandler);
_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _securityErrorHandler);
_completeEvent = new Event(Event.COMPLETE, false, true);
_liveStatuses = [];//add other acceptable http statuses here
}
public function check(url:String = 'http://stackoverflow.com'):void {
_dispatched = false;
_url = url;
_request = new URLRequest(url);
_loader.load(_request);
_log += 'load for ' + _url + ' started : ' + new Date() + '\n';
}
private function _completeHandler(e:Event):void
{
_log += e.toString() + ' at ' + new Date();
_isLive = true;
if (!_dispatched) {
dispatchEvent(_completeEvent);
_dispatched = true;
}
}
private function _httpStatusHandler(e:HTTPStatusEvent):void
{
/* comment this in when you're sure what statuses you're after
var statusesLen:int = _liveStatuses.length;
for (var i:int = statusesLen; i > 0; i--) {
if (e.status == _liveStatuses[i]) {
_isLive = true;
dispatchEvent(_completeEvent);
}
}
*/
//200 range
_log += e.toString() + ' at ' + new Date();
if (e.status >= 200 && e.status < 300) _isLive = true;
else _isLive = false;
if (!_dispatched) {
dispatchEvent(_completeEvent);
_dispatched = true;
}
}
private function _ioErrorEventHandler(e:IOErrorEvent):void
{
_log += e.toString() + ' at ' + new Date();
_isLive = false;
if (!_dispatched) {
dispatchEvent(_completeEvent);
_dispatched = true;
}
}
private function _securityErrorHandler(e:SecurityErrorEvent):void
{
_log += e.toString() + ' at ' + new Date();
_isLive = false;
if (!_dispatched) {
dispatchEvent(_completeEvent);
_dispatched = true;
}
}
public function get isLive():Boolean { return _isLive; }
public function get log():String { return _log; }
}
}
and here's a basic usage example:
var urlChecker:URLChecker = new URLChecker();
urlChecker.addEventListener(Event.COMPLETE, urlChecked);
urlChecker.check('wrong_place.url');
function urlChecked(event:Event):void {
trace('is Live: ' + event.target.isLive);
trace('log: ' + event.target.log);
}
The idea is simple:
1. You create a checked
2. Listen for the COMPLETE event(triggered when it has a result
3. In the handler check if it's live and what it logged.
In the HTTP specs, 200 area seems ok, but depending on what you load, you might need
to adjust the class. Also you need to handle security/cross domain issue better, but at least it's a start.
HTH
An important consideration that George's answer left out is the URLRequestMethod. If one were trying to verify the existence of rather large files (e.g, media files) and not just a webpage, you'd want to make sure to set the method property on the URLRequest to URLRequestMethod.HEAD.
As stated in the HTTP1.1 Protocol:
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
Hence, if you really only want to verify the existence of the URL, this is the way to go.
For those who need the code spelled out:
var _request:URLRequest = URLRequest(url);
_request.method = URLRequestMethod.HEAD; // bandwidth :)
Otherwise, George's answer is a good reference point.
NB: This particular URLRequestMethod is only available in AIR.

Resources