Esempio n. 1
0
 protected void pollForInput(object state)
 {
     if (State == DeviceState.Ready)
     {
         lock (bufferLock)
         {
             bufferLock = true;
             try
             {
                 int numBytes = socket.Receive(buffer);
                 if (numBytes > 0)
                 {
                     char[] chars = Encoding.ASCII.GetChars(buffer, 0, numBytes);
                     for (int i = 0; i < chars.Length; i++)
                     {
                         doCharRecieved(chars[i]);
                     }
                 }
             }
             catch (Exception ex)
             {
                 State = DeviceState.Error;
                 WDAppLog.logException(ErrorLevel.Error, ex);
                 pollTimer.Dispose();
             }
         }
     }
 }
Esempio n. 2
0
        public override void Render(IRenderer g)
        {
            if (Image == null)
            {
                return;
            }

            try
            {
                if (renderMatrixProxy == null)
                {
                    renderMatrixProxy = this.CalculateWorldToScreenTransformMatrix();
                }
                g.SetTransform(renderMatrixProxy);
                g.DrawImage(Image, 0, 0);
                g.ResetTransform();

                /*
                 * //Renderer method, has issues because g.DrawImage is not what it appears
                 * Point[] points = new Point[3] {new Point(0,0),
                 *                          new Point(Image.Width,0),
                 *                          new Point(0,Image.Height)};
                 * points[0] = renderMatrixProxy.Transform(points[0]).AsPoint();
                 * points[1] = renderMatrixProxy.Transform(points[1]).AsPoint();
                 * points[2] = renderMatrixProxy.Transform(points[2]).AsPoint();
                 *
                 * g.DrawImage(Image, points);
                 */
            }
            catch (Exception ex)
            {
                WDAppLog.logException(ErrorLevel.Error, ex);
            }
        }
Esempio n. 3
0
        protected string itemToString(object item)
        {
            string name = "?";

            try
            {
                if (GetName != null)
                {
                    name = GetName(item);
                    if (name.IsSomething())
                    {
                        return(name.Trim());
                    }
                }
            }
            catch (Exception ex)
            {
                WDAppLog.logException(ErrorLevel.Error, ex);
            }

            try
            {
                name = (item ?? "NULL").ToString();
            }
            catch (Exception ex)
            {
                WDAppLog.logException(ErrorLevel.Error, ex);
            }

            return(name);
        }
Esempio n. 4
0
        public static Tile fromFile(string path, string name, int id, bool bind = false)
        {
            if (File.Exists(path))
            {
                string tileName = name ?? Path.GetFileNameWithoutExtension(path);

                try
                {
                    using (Bitmap b = new Bitmap(path))
                    {
                        if (b != null)
                        {
                            Tile t = fromBitmap(b.GetUnFuckedVersion(), tileName, id);
                            if (t != null)
                            {
                                t._dataBinding = new FileBoundData <Tile>(t, path, bind);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WDAppLog.logFileOpenError(ErrorLevel.Error, ex, path);
                }
            }
            return(null);
        }
Esempio n. 5
0
        public static double GetPerMetreConversion(DistanceUnits units)
        {
            switch (units)
            {
            case DistanceUnits.ImpInches:
                return(InchesPerMetre);

            case DistanceUnits.ImpFeet:
                return(FeetPerMetre);

            case DistanceUnits.ImpMils:
                return(MilsPerMetre);

            case DistanceUnits.ImpMiles:
                return(MilesPereMetre);

            case DistanceUnits.Metres:
                return(1);

            case DistanceUnits.CentiMetres:
                return(CentiMetresPerMetre);

            case DistanceUnits.MilliMetres:
                return(MilliMetresPerMetre);

            case DistanceUnits.KiloMetres:
                return(KiloMetresPerMetre);
            }

            WDAppLog.LogNeverSupposedToBeHere();
            return(1);//wtf
        }
Esempio n. 6
0
        protected void OnConnect(IAsyncResult ar)
        {
            // Socket was the passed in object
            Socket sock = (Socket)ar.AsyncState;

            State = DeviceState.Unknown;


            // Check if we were sucessfull
            try
            {
                //    sock.EndConnect( ar );
                if (sock.Connected)
                {
                    SetupRecieveCallback(sock);
                    State = DeviceState.Ready;
                }
                else
                {
                    State = DeviceState.Error;
                }
            }
            catch (Exception ex)
            {
                State = DeviceState.Error;
                WDAppLog.logException(ErrorLevel.SmallError, ex);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Compares equaity of all items.
        /// Note: Use CompareBytDataItems() == 0 insted, if the IGetDataItems implements IComparable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool EqualBytDataItems <T>(this T a, T b)
            where T : IGetDataItems
        {
#if DEBUG
            if (!a.DataNames.SequenceEqual(b.DataNames))
            {
                //I don't see immenent need for handeling situations where DataNames are different for objects of the same type.
                WDAppLog.LogNeverSupposedToBeHere();
                throw new InvalidOperationException();
            }
#endif

            var names = a.DataNames;
            for (int i = 0; i < names.Length; i++)
            {
                int comp = 0;

                string name  = names[i];
                var    aItem = a.GetDataItem(name);
                var    bItem = b.GetDataItem(name);

                //uses a clever trick to catch edge cases, look twice
                if ((!object.ReferenceEquals(aItem, bItem)) && (!aItem.Equals(bItem)))
                {
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 8
0
        public void CreateErrors()
        {
            WDAppLog.UseErrorLogString = true;
            foreach (ErrorLevel level in Enum.GetValues(typeof(ErrorLevel)))
            {
                WDAppLog.logError(level, "Testing log error for " + level);
                WDAppLog.logError(level, "This one has aditional Info", "Extra information goes here");

                NullReferenceException ex = new NullReferenceException("Just a test");
                WDAppLog.logException(level, ex);

                string file = @"c:\filedoesnotexist.txt";
                try
                {
                    string[] na = File.ReadAllLines(file);
                }
                catch (Exception ex2)
                {
                    WDAppLog.logFileOpenError(ErrorLevel.Error, ex2, file);
                }

                //create an exception deep in a call stack
                CreateExceptionA(level);
            }

            //Debug.WriteLine(WDAppLog.errorLogString);
        }
Esempio n. 9
0
 public void ChangeMouseCursor(Cursor cursor)
 {
     MouseCursor = cursor;
     if (OnMouseCursorChange != null)
     {
         WDAppLog.TryCatchLogged(delegate() { OnMouseCursorChange(this, null); }, ErrorLevel.Error);
     }
 }
Esempio n. 10
0
        void sshShell_ErrorOccurred(object sender, ExceptionEventArgs e)
        {
            string msg = "(NO INFO)";

            if ((e != null) && (e.Exception != null) && (!string.IsNullOrWhiteSpace(e.Exception.Message)))
            {
                msg = e.Exception.Message;
            }
            WDAppLog.logError(ErrorLevel.Error, string.Format("Error in SSH connection [{0}]: {1}", this.ToString(), msg));
        }
Esempio n. 11
0
        public static Tile loadTile(Type type, string path, int id)
        {
            if (type == typeof(Tile))
            {
                return(Tile.fromFile(path, id));
            }

            WDAppLog.logFileOpenError(ErrorLevel.Error, path);
            return(null);
        }
Esempio n. 12
0
        protected void DoViewChangeTasks(bool updateScrollBars = true)
        {
            updatingControls = true;
            try
            {
                if (view != null)
                {
                    lblZoom.Text = ((int)(view.Zoom * 100.0)).ToString() + "%";

                    if (updateScrollBars)
                    {
                        double xOff = 0; // (view.WorldSpaceBounds.X * view.Zoom);
                        double yOff = 0; //(view.WorldSpaceBounds.Y * view.Zoom);

                        int newVScroll = -(int)(view.TransformY - xOff);
                        int newHScroll = -(int)(view.TransformX - yOff);

                        //these 2 lines are to enable a infinite scolling, which may be bad.
                        adjustRangeToSuite(scrlVert, newVScroll);
                        adjustRangeToSuite(scrlHoriz, newHScroll);


                        scrlVert.Value  = newVScroll;
                        scrlHoriz.Value = newHScroll;
                    }

                    if (view is IEditableView2D)
                    {
                        IEditableView2D ev = view as IEditableView2D;
                        //resend the mouse pos.
                        //The mouse did not move on the screen, but the view window is different


                        MouseEventArgs arg = new MouseEventArgs(System.Windows.Forms.MouseButtons.None,
                                                                0,
                                                                ((Control)picMain).PointToClient(Cursor.Position).X,
                                                                ((Control)picMain).PointToClient(Cursor.Position).Y,
                                                                0);

                        ev.DoMouseMove_ScreenSpace(this, arg);
                    }

                    if (onViewChange != null)
                    {
                        onViewChange(view);
                    }
                }
            }
            catch (Exception ex)
            {
                WDAppLog.logException(ErrorLevel.SmallError, ex);
            }

            updatingControls = false;
        }
Esempio n. 13
0
 private static void CreateExceptionA(ErrorLevel level)
 {
     try
     {
         CreateExceptionB();
     }
     catch (Exception ex2)
     {
         WDAppLog.logException(level, ex2);
     }
 }
Esempio n. 14
0
        public static int[] ParseAllIntegers(this string str)
        {
            List <string> intStringList = new List <string>();
            string        current       = "";

            foreach (char c in str)
            {
                if (c == '-')
                {
                    if (current.Length == 0)
                    {
                        current = "-";
                        continue;
                    }
                    //no continue, theinteger is not continuing
                }
                else if ("0123456789".Contains(c))
                {
                    current += c;
                    continue;
                }

                //here only if the int is finished
                if ((current.Length > 0) && (current != "-"))
                {
                    intStringList.Add(current);
                }
                current = (c == '-') ? "-"  : "";
            }

            //done
            if ((current.Length > 0) && (current != "-"))
            {
                intStringList.Add(current);
            }

            List <int> nums = new List <int>();

            for (int i = 0; i < intStringList.Count; i++)
            {
                try
                {
                    int num = int.Parse(intStringList[i]);
                    nums.Add(num);
                }
                catch (Exception ex)
                {
                    WDAppLog.logException(ErrorLevel.Error, ex);
                }
            }

            return(nums.ToArray());
        }
Esempio n. 15
0
        public static IList <Bitmap> GetAllSpritesInFile(string file, Size spriteSize)
        {
            Bitmap img = Bitmap.FromFile(file) as Bitmap;

            if (img != null)
            {
                img = img.GetUnFuckedVersion();
                return(GetAllSpritesInImage(img, spriteSize));
            }
            WDAppLog.logFileOpenError(ErrorLevel.Error, file);
            return(new List <Bitmap>());
        }
Esempio n. 16
0
 private byte [] m_byBuff = new byte[1024];       // Recieved data buffer
 public void SetupRecieveCallback(Socket sock)
 {
     try
     {
         AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
         sock.BeginReceive(m_byBuff, 0, m_byBuff.Length,
                           SocketFlags.None, recieveData, sock);
     }
     catch (Exception ex)
     {
         WDAppLog.logException(ErrorLevel.SmallError, ex);
     }
 }
Esempio n. 17
0
 public static Why FalseBecause(string reason, bool logAndReportSecureError = false)
 {
     if (logAndReportSecureError)
     {
         string tag = rand.NextNextAlphaNumerics(6);
         WDAppLog.logError(ErrorLevel.Error, string.Format("Error logged with user obfuscation tag={0}: {1}", tag, reason));
         return(new Why(false, string.Format("Internal system error, see logs for details (tag={0}).", tag)));
     }
     else
     {
         return(new Why(false, reason));
     }
 }
Esempio n. 18
0
        public void loadTMXFile(string path, bool bind)
        {
            XmlDocument xml = new XmlDocument();

            xml.LoadXml(File.ReadAllText(path));
            XmlNode mapNode = xml["map"];

            //get basic info
            int mapWidth   = int.Parse(mapNode.Attributes["width"].InnerText);
            int mapHeight  = int.Parse(mapNode.Attributes["height"].InnerText);
            int tileWidth  = int.Parse(mapNode.Attributes["tilewidth"].InnerText);
            int tileHeight = int.Parse(mapNode.Attributes["tileheight"].InnerText);

            //load world (assumes same sized tiles throughout layers)
            foreach (XmlNode subNode in mapNode)
            {
                if (subNode.Name.EqualsIgnoreCase("tileset"))
                {
                    string imageAtlasFile = subNode["image"].Attributes["source"].InnerText;
                    string imageAtlasPath = Path.Combine(Path.GetDirectoryName(path), imageAtlasFile);
                    int    startIndex     = int.Parse(subNode.Attributes["firstgid"].InnerText);
                    TileSets.Add(TileSet <Tile> .fromImageAtlas(imageAtlasPath, startIndex, tileWidth, tileHeight));
                    rebuildTileLut(); //(future proofing) do now incase layers ever need to inspect the tiles
                }
                else if (subNode.Name.EqualsIgnoreCase("layer"))
                {
                    string layerFormat = subNode["data"].Attributes["encoding"].InnerText;
                    if (layerFormat.EqualsIgnoreCase("csv"))
                    {
                        //get all numbers from the csv [LIKE A BOSS]
                        //int[] indicies = subNode["data"].InnerText.Split(',').Select(n => int.Parse(n.Trim())).ToArray();
                        int[] indicies = subNode["data"].InnerText.ParseAllIntegers();
                        Panes.Add(new TiledPane(mapWidth, mapHeight, indicies, this));
                    }
                    else
                    {
                        WDAppLog.logError(ErrorLevel.Error, "Unsuported layer format", path);
                    }
                }
                else if (subNode.Name.EqualsIgnoreCase("objectgroup"))
                {
                }
                else if (subNode.Name.EqualsIgnoreCase("imagelayer"))
                {
                    string imageFile = subNode["image"].Attributes["source"].InnerText.Trim();
                    string imagePath = Path.Combine(Path.GetDirectoryName(path), imageFile);
                    Bitmap b         = new Bitmap(imagePath);
                    Panes.Add(new ImagePane(b));
                }
            }
        }
Esempio n. 19
0
        //-------------------------------------------------------------------------------------------------------
        // internal
        //-------------------------------------------------------------------------------------------------------
        private void patternThreadMethod()
        {
            bool finished = false;

            while (!finished)
            {
                WDThreadPatternStates _state = state;
                switch (_state)
                {
                case WDThreadPatternStates.Created:
                    safeRun(OnStart, _state);
                    state = WDThreadPatternStates.Alive;
                    break;

                case WDThreadPatternStates.Alive:
                    try
                    {
                        if (OnLoop != null)
                        {
                            if (OnLoop())
                            {
                                //BUG: wont do the time out stuff
                                state = WDThreadPatternStates.Stopping;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WDAppLog.logError(ErrorLevel.Error,
                                          "IWDThreadPattern loop method threw an exception",
                                          ex.Message);
                    }

                    break;

                case WDThreadPatternStates.Stopping:
                    safeRun(OnStop, _state);
                    state    = WDThreadPatternStates.Stoped;
                    finished = true;
                    break;

                case WDThreadPatternStates.Stoped:
                    finished = true;
                    break;

                default:
                    break;
                }
                Thread.SpinWait(1);
            }
        }
Esempio n. 20
0
        /*event MouseEventWorldSpace.WSMouseEventHandler IView2D.MouseClickWS
         * {
         *  add { lock (this.mouseClickWS) { this.mouseClickWS += value; } }
         *  remove { lock (this.mouseClickWS) { this.mouseClickWS -= value; } }
         * }*/


        #endregion

        /*public void RaiseMouseEvwent(object sender, MouseEventWorldSpace e)
         * {
         *  if (mouseClickWS != null)
         *  {
         *      mouseClickWS(sender, e);
         *  }
         * }*/

        public void Refresh()
        {
            if (OnRefreshNeeded != null)
            {
                try
                {
                    OnRefreshNeeded();
                }
                catch (Exception ex)
                {
                    WDAppLog.logException(ErrorLevel.Error, ex);
                }
            }
        }
Esempio n. 21
0
 private AppConfig()
 {
     try
     {
         if (!Directory.Exists(configSaveDir))
         {
             Directory.CreateDirectory(configSaveDir);
         }
     }
     catch (Exception ex)
     {
         WDAppLog.logException(ErrorLevel.TerminalError, ex);
     }
 }
Esempio n. 22
0
        protected void doCharRecieved(char c)
        {
            //debug code

            /*
             * ConsoleColor old = Console.ForegroundColor;
             * Console.ForegroundColor = cols[(colsPos++) % cols.Length];
             * Console.BackgroundColor = ConsoleColor.Blue;
             * Console.Write(c);
             * Console.ForegroundColor = old;
             * Console.BackgroundColor = ConsoleColor.Black;
             */

            updateDeviceAfterInput(c);
            if (OnCharRecived != null)
            {
                try
                {
                    OnCharRecived(c);
                }
                catch (Exception ex)
                {
                    WDAppLog.logException(ErrorLevel.Error, ex);
                }
            }

            if ((c == '\r') || (c == '\n'))
            {
                if (currentLine.Length > 0)
                {
                    try
                    {
                        if (OnLineRecived != null) //check this now, because it may bee null as the first chars are coming in
                        {
                            OnLineRecived(currentLine.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        WDAppLog.logException(ErrorLevel.Error, ex);
                    }
                }
                currentLine.Clear();
            }
            else
            {
                currentLine.Append(c);
            }
        }
Esempio n. 23
0
        public void OnRecievedData(IAsyncResult ar)
        {
            // Socket was the passed in object
            Socket sock = (Socket)ar.AsyncState;

            if (!sock.Connected)
            {
                return; //something got fowld up in this tangled web
            }

            // Check if we got any data
            try
            {
                int nBytesRec = sock.EndReceive(ar);
                if (nBytesRec > 0)
                {
                    //input
                    char[] chars = Encoding.ASCII.GetChars(m_byBuff, 0, nBytesRec);
                    for (int i = 0; i < chars.Length; i++)
                    {
                        //the base class provides for this
                        doCharRecieved(chars[i]);
                    }

                    // If the connection is still usable restablish the callback
                    SetupRecieveCallback(sock);
                }
                else
                {
                    // If no data was recieved then the connection is probably dead
                    if (State == DeviceState.Ready)
                    {
                        //sock.Shutdown(SocketShutdown.Both);
                        State = DeviceState.NotConnected;
                    }
                    else
                    {
                        WDAppLog.logError(ErrorLevel.SmallError, "Connection lost: " + this.ToString());
                    }
                    //sock.Shutdown(SocketShutdown.Both);
                    //sock.Close();
                    //SetupRecieveCallback(sock);
                }
            }
            catch (Exception ex)
            {
                WDAppLog.logException(ErrorLevel.SmallError, ex);
            }
        }
Esempio n. 24
0
        public static String GetPreferedShortUnitString(DistanceUnits unit)
        {
            var info    = from U in unitsTable where U.Unit == unit select U;
            var theInfo = info.FirstOrDefault(U => U.PreferedShortFormat) ?? info.First();

            if (theInfo != null)
            {
                return(theInfo.UnitText);
            }
            else
            {
                WDAppLog.LogNeverSupposedToBeHere();
                return("(unnamed unit: " + unit.ToString() + ")");
            }
        }
Esempio n. 25
0
        public static ProformaClass FromNameAndAge(string name, int age)
        {
            ProformaClass p     = new ProformaClass(name, age);
            Why           valid = p.Valid();

            if (valid)
            {
                return(p);
            }
            else
            {
                WDAppLog.logError(ErrorLevel.Error, "Invalid data: " + valid.Reason);
                return(null);
            }
        }
Esempio n. 26
0
 public GDIPlusRenderer(int width, int height)
 {
     try
     {
         bitmap      = new Bitmap(width, height);
         graphics    = Graphics.FromImage(bitmap);
         AngleType   = AngleTypes.Degrees;
         HighQuality = true;
     }
     catch (Exception ex)
     {
         WDAppLog.logException(ErrorLevel.Error, ex);
         throw ex;
     }
 }
Esempio n. 27
0
        public bool ReloadFile(string path)
        {
            this.FileName = path;
            Bitmap img = Bitmap.FromFile(path) as Bitmap;

            if (img != null)
            {
                img   = img.GetUnFuckedVersion();
                Image = img;

                FrameBounds = SpriteHelper.CalcFrameBounds(img, SpriteWidth, SpriteHeight);
                return(true);
            }
            WDAppLog.logFileOpenError(ErrorLevel.Error, path);
            return(false);
        }
Esempio n. 28
0
        public void RebindPropertyGrid()
        {
            if (!SelectedIndexValid)
            {
                selectedIndex = -1;
            }

            try
            {
                pgMain.SelectedObject = SelectedItem;
            }
            catch (Exception ex)
            {
                WDAppLog.logException(ErrorLevel.Error, ex);
            }
        }
Esempio n. 29
0
        public static TileSet <Tile> fromImageAtlas(string path, int startIndex, int tileWidth, int tileHeight, Func <int, string> getName = null)
        {
            TileSet <Tile> tileSet = new TileSet <Tile>(tileWidth, tileHeight);

            try
            {
                if (File.Exists(path))
                {
                    using (Bitmap b = new Bitmap(path))
                    {
                        string basicName = Path.GetFileNameWithoutExtension(path);
                        int    width     = b.Width;
                        int    height    = b.Height;
                        int    index     = 0;
                        for (int y = 0; y <= (height - tileHeight); y += tileHeight)
                        {
                            for (int x = 0; x <= (width - tileWidth); x += tileWidth)
                            {
                                //get sub-image
                                Bitmap tb = b.GetSubImageClipped(x, y, tileWidth, tileHeight);

                                if (tb == null)
                                {
                                    WDAppLog.LogNeverSupposedToBeHere();
                                }
                                //get a name
                                string name = (getName != null) ? getName(index) : null;
                                name = String.IsNullOrWhiteSpace(name) ? (basicName + "_" + index) : name;

                                //create and add tile
                                Tile tile = Tile.fromBitmap(tb, name, startIndex + index);
                                tileSet.Add(tile);

                                index++;
                            }
                        }
                    }
                    return(tileSet);
                }
            }
            catch (Exception ex)
            {
                WDAppLog.logFileOpenError(ErrorLevel.Error, ex, path);
            }

            return(null);
        }
Esempio n. 30
0
 void safeRun(Action action, WDThreadPatternStates state)
 {
     if (action != null)
     {
         try
         {
             action();
         }
         catch (Exception ex)
         {
             string[] method = { "Start", "Loop", "Stop", "?" };
             WDAppLog.logError(ErrorLevel.Error,
                               "IWDThreadPattern method threw an exception executing: " + method[(int)state],
                               ex.Message);
         }
     }
 }