Search Results

Search found 3489 results on 140 pages for 'summary'.

Page 1/140 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • XNA Screen Manager problem with transitions

    - by NexAddo
    I'm having issues using the game statemanagement example in the game I am developing. I have no issues with my first three screens transitioning between one another. I have a main menu screen, a splash screen and a high score screen that cycle: mainMenuScreen->splashScreen->highScoreScreen->mainMenuScreen The screens change every 15 seconds. Transition times public MainMenuScreen() { TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.0); currentCreditAmount = Global.CurrentCredits; } public SplashScreen() { TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } public HighScoreScreen() { TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } public GamePlayScreen() { TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } When a user inserts credits they can play the game after pressing start mainMenuScreen->splashScreen->highScoreScreen->(loops forever) || || || ===========Credits In============= || Start || \/ LoadingScreen || Start || \/ GamePlayScreen During each of these transitions, between screens, the same code is used, which exits(removes) all current active screens and respects transitions, then adds the new screen to the screen manager: foreach (GameScreen screen in ScreenManager.GetScreens()) screen.ExitScreen(); //AddScreen takes a new screen to manage and the controlling player ScreenManager.AddScreen(new NameOfScreenHere(), null); Each screen is removed from the ScreenManager with ExitScreen() and using this function, each screen transition is respected. The problem I am having is with my gamePlayScreen. When the current game is finished and the transition is complete for the gamePlayScreen, it should be removed and the next screens should be added to the ScreenManager. GamePlayScreen Code Snippet private void FinishCurrentGame() { AudioManager.StopSounds(); this.UnloadContent(); if (Global.SaveDevice.IsReady) Stats.Save(); if (HighScoreScreen.IsInHighscores(timeLimit)) { foreach (GameScreen screen in ScreenManager.GetScreens()) screen.ExitScreen(); Global.TimeRemaining = timeLimit; ScreenManager.AddScreen(new BackgroundScreen(), null); ScreenManager.AddScreen(new MessageBoxScreen("Enter your Initials", true), null); } else { foreach (GameScreen screen in ScreenManager.GetScreens()) screen.ExitScreen(); ScreenManager.AddScreen(new BackgroundScreen(), null); ScreenManager.AddScreen(new MainMenuScreen(), null); } } The problem is that when isExiting is set to true by screen.ExitScreen() for the gamePlayScreen, the transition never completes the transition and removes the screen from the ScreenManager. Every other screen that I use the same technique to add and remove each screen fully transitions On/Off and is removed at the appropriate time from the ScreenManager, but noy my GamePlayScreen. Has anyone that has used the GameStateManagement example experienced this issue or can someone see the mistake I am making? EDIT This is what I tracked down. When the game is done, I call foreach (GameScreen screen in ScreenManager.GetScreens()) screen.ExitScreen(); to start the transition off process for the gameplay screen. At this point there is only 1 screen on the ScreenManager stack. The gamePlay screen gets isExiting set to true and starts to transition off. Right after the above call to ExitScreen() I add a background screen and menu screen to the screenManager: ScreenManager.AddScreen(new background(), null); ScreenManager.AddScreen(new Menu(), null); The count of the ScreenManager is now 3. What I noticed while stepping through the updates for GameScreen and ScreenManager, the gameplay screen never gets to the point where the transistion process finishes so the ScreenManager can remove it from the stack. This anomaly does not happen to any of my other screens when I switch between them. Screen Manager Code #region File Description //----------------------------------------------------------------------------- // ScreenManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #define DEMO #region Using Statements using System; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using PerformanceUtility.GameDebugTools; #endregion namespace GameStateManagement { /// <summary> /// The screen manager is a component which manages one or more GameScreen /// instances. It maintains a stack of screens, calls their Update and Draw /// methods at the appropriate times, and automatically routes input to the /// topmost active screen. /// </summary> public class ScreenManager : DrawableGameComponent { #region Fields List<GameScreen> screens = new List<GameScreen>(); List<GameScreen> screensToUpdate = new List<GameScreen>(); InputState input = new InputState(); SpriteBatch spriteBatch; SpriteFont font; Texture2D blankTexture; bool isInitialized; bool getOut; bool traceEnabled; #if DEBUG DebugSystem debugSystem; Stopwatch stopwatch = new Stopwatch(); bool debugTextEnabled; #endif #endregion #region Properties /// <summary> /// A default SpriteBatch shared by all the screens. This saves /// each screen having to bother creating their own local instance. /// </summary> public SpriteBatch SpriteBatch { get { return spriteBatch; } } /// <summary> /// A default font shared by all the screens. This saves /// each screen having to bother loading their own local copy. /// </summary> public SpriteFont Font { get { return font; } } public Rectangle ScreenRectangle { get { return new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); } } /// <summary> /// If true, the manager prints out a list of all the screens /// each time it is updated. This can be useful for making sure /// everything is being added and removed at the right times. /// </summary> public bool TraceEnabled { get { return traceEnabled; } set { traceEnabled = value; } } #if DEBUG public bool DebugTextEnabled { get { return debugTextEnabled; } set { debugTextEnabled = value; } } public DebugSystem DebugSystem { get { return debugSystem; } } #endif #endregion #region Initialization /// <summary> /// Constructs a new screen manager component. /// </summary> public ScreenManager(Game game) : base(game) { // we must set EnabledGestures before we can query for them, but // we don't assume the game wants to read them. //TouchPanel.EnabledGestures = GestureType.None; } /// <summary> /// Initializes the screen manager component. /// </summary> public override void Initialize() { base.Initialize(); #if DEBUG debugSystem = DebugSystem.Initialize(Game, "Fonts/MenuFont"); #endif isInitialized = true; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load content belonging to the screen manager. ContentManager content = Game.Content; spriteBatch = new SpriteBatch(GraphicsDevice); font = content.Load<SpriteFont>(@"Fonts\menufont"); blankTexture = content.Load<Texture2D>(@"Textures\Backgrounds\blank"); // Tell each of the screens to load their content. foreach (GameScreen screen in screens) { screen.LoadContent(); } } /// <summary> /// Unload your graphics content. /// </summary> protected override void UnloadContent() { // Tell each of the screens to unload their content. foreach (GameScreen screen in screens) { screen.UnloadContent(); } } #endregion #region Update and Draw /// <summary> /// Allows each screen to run logic. /// </summary> public override void Update(GameTime gameTime) { #if DEBUG debugSystem.TimeRuler.StartFrame(); debugSystem.TimeRuler.BeginMark("Update", Color.Blue); if (debugTextEnabled && getOut == false) { debugSystem.FpsCounter.Visible = true; debugSystem.TimeRuler.Visible = true; debugSystem.TimeRuler.ShowLog = true; getOut = true; } else if (debugTextEnabled == false) { getOut = false; debugSystem.FpsCounter.Visible = false; debugSystem.TimeRuler.Visible = false; debugSystem.TimeRuler.ShowLog = false; } #endif // Read the keyboard and gamepad. input.Update(); // Make a copy of the master screen list, to avoid confusion if // the process of updating one screen adds or removes others. screensToUpdate.Clear(); foreach (GameScreen screen in screens) screensToUpdate.Add(screen); bool otherScreenHasFocus = !Game.IsActive; bool coveredByOtherScreen = false; // Loop as long as there are screens waiting to be updated. while (screensToUpdate.Count > 0) { // Pop the topmost screen off the waiting list. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1]; screensToUpdate.RemoveAt(screensToUpdate.Count - 1); // Update the screen. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active) { // If this is the first active screen we came across, // give it a chance to handle input. if (!otherScreenHasFocus) { screen.HandleInput(input); otherScreenHasFocus = true; } // If this is an active non-popup, inform any subsequent // screens that they are covered by it. if (!screen.IsPopup) coveredByOtherScreen = true; } } // Print debug trace? if (traceEnabled) TraceScreens(); #if DEBUG debugSystem.TimeRuler.EndMark("Update"); #endif } /// <summary> /// Prints a list of all the screens, for debugging. /// </summary> void TraceScreens() { List<string> screenNames = new List<string>(); foreach (GameScreen screen in screens) screenNames.Add(screen.GetType().Name); Debug.WriteLine(string.Join(", ", screenNames.ToArray())); } /// <summary> /// Tells each screen to draw itself. /// </summary> public override void Draw(GameTime gameTime) { #if DEBUG debugSystem.TimeRuler.StartFrame(); debugSystem.TimeRuler.BeginMark("Draw", Color.Yellow); #endif foreach (GameScreen screen in screens) { if (screen.ScreenState == ScreenState.Hidden) continue; screen.Draw(gameTime); } #if DEBUG debugSystem.TimeRuler.EndMark("Draw"); #endif #if DEMO SpriteBatch.Begin(); SpriteBatch.DrawString(font, "DEMO - NOT FOR RESALE", new Vector2(20, 80), Color.White); SpriteBatch.End(); #endif } #endregion #region Public Methods /// <summary> /// Adds a new screen to the screen manager. /// </summary> public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer) { screen.ControllingPlayer = controllingPlayer; screen.ScreenManager = this; screen.IsExiting = false; // If we have a graphics device, tell the screen to load content. if (isInitialized) { screen.LoadContent(); } screens.Add(screen); } /// <summary> /// Removes a screen from the screen manager. You should normally /// use GameScreen.ExitScreen instead of calling this directly, so /// the screen can gradually transition off rather than just being /// instantly removed. /// </summary> public void RemoveScreen(GameScreen screen) { // If we have a graphics device, tell the screen to unload content. if (isInitialized) { screen.UnloadContent(); } screens.Remove(screen); screensToUpdate.Remove(screen); } /// <summary> /// Expose an array holding all the screens. We return a copy rather /// than the real master list, because screens should only ever be added /// or removed using the AddScreen and RemoveScreen methods. /// </summary> public GameScreen[] GetScreens() { return screens.ToArray(); } /// <summary> /// Helper draws a translucent black fullscreen sprite, used for fading /// screens in and out, and for darkening the background behind popups. /// </summary> public void FadeBackBufferToBlack(float alpha) { Viewport viewport = GraphicsDevice.Viewport; spriteBatch.Begin(); spriteBatch.Draw(blankTexture, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.Black * alpha); spriteBatch.End(); } #endregion } } Game Screen Parent of GamePlayScreen #region File Description //----------------------------------------------------------------------------- // GameScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; //using Microsoft.Xna.Framework.Input.Touch; using System.IO; #endregion namespace GameStateManagement { /// <summary> /// Enum describes the screen transition state. /// </summary> public enum ScreenState { TransitionOn, Active, TransitionOff, Hidden, } /// <summary> /// A screen is a single layer that has update and draw logic, and which /// can be combined with other layers to build up a complex menu system. /// For instance the main menu, the options menu, the "are you sure you /// want to quit" message box, and the main game itself are all implemented /// as screens. /// </summary> public abstract class GameScreen { #region Properties /// <summary> /// Normally when one screen is brought up over the top of another, /// the first screen will transition off to make room for the new /// one. This property indicates whether the screen is only a small /// popup, in which case screens underneath it do not need to bother /// transitioning off. /// </summary> public bool IsPopup { get { return isPopup; } protected set { isPopup = value; } } bool isPopup = false; /// <summary> /// Indicates how long the screen takes to /// transition on when it is activated. /// </summary> public TimeSpan TransitionOnTime { get { return transitionOnTime; } protected set { transitionOnTime = value; } } TimeSpan transitionOnTime = TimeSpan.Zero; /// <summary> /// Indicates how long the screen takes to /// transition off when it is deactivated. /// </summary> public TimeSpan TransitionOffTime { get { return transitionOffTime; } protected set { transitionOffTime = value; } } TimeSpan transitionOffTime = TimeSpan.Zero; /// <summary> /// Gets the current position of the screen transition, ranging /// from zero (fully active, no transition) to one (transitioned /// fully off to nothing). /// </summary> public float TransitionPosition { get { return transitionPosition; } protected set { transitionPosition = value; } } float transitionPosition = 1; /// <summary> /// Gets the current alpha of the screen transition, ranging /// from 1 (fully active, no transition) to 0 (transitioned /// fully off to nothing). /// </summary> public float TransitionAlpha { get { return 1f - TransitionPosition; } } /// <summary> /// Gets the current screen transition state. /// </summary> public ScreenState ScreenState { get { return screenState; } protected set { screenState = value; } } ScreenState screenState = ScreenState.TransitionOn; /// <summary> /// There are two possible reasons why a screen might be transitioning /// off. It could be temporarily going away to make room for another /// screen that is on top of it, or it could be going away for good. /// This property indicates whether the screen is exiting for real: /// if set, the screen will automatically remove itself as soon as the /// transition finishes. /// </summary> public bool IsExiting { get { return isExiting; } protected internal set { isExiting = value; } } bool isExiting = false; /// <summary> /// Checks whether this screen is active and can respond to user input. /// </summary> public bool IsActive { get { return !otherScreenHasFocus && (screenState == ScreenState.TransitionOn || screenState == ScreenState.Active); } } bool otherScreenHasFocus; /// <summary> /// Gets the manager that this screen belongs to. /// </summary> public ScreenManager ScreenManager { get { return screenManager; } internal set { screenManager = value; } } ScreenManager screenManager; public KeyboardState KeyboardState { get {return Keyboard.GetState();} } /// <summary> /// Gets the index of the player who is currently controlling this screen, /// or null if it is accepting input from any player. This is used to lock /// the game to a specific player profile. The main menu responds to input /// from any connected gamepad, but whichever player makes a selection from /// this menu is given control over all subsequent screens, so other gamepads /// are inactive until the controlling player returns to the main menu. /// </summary> public PlayerIndex? ControllingPlayer { get { return controllingPlayer; } internal set { controllingPlayer = value; } } PlayerIndex? controllingPlayer; /// <summary> /// Gets whether or not this screen is serializable. If this is true, /// the screen will be recorded into the screen manager's state and /// its Serialize and Deserialize methods will be called as appropriate. /// If this is false, the screen will be ignored during serialization. /// By default, all screens are assumed to be serializable. /// </summary> public bool IsSerializable { get { return isSerializable; } protected set { isSerializable = value; } } bool isSerializable = true; #endregion #region Initialization /// <summary> /// Load graphics content for the screen. /// </summary> public virtual void LoadContent() { } /// <summary> /// Unload content for the screen. /// </summary> public virtual void UnloadContent() { } #endregion #region Update and Draw /// <summary> /// Allows the screen to run logic, such as updating the transition position. /// Unlike HandleInput, this method is called regardless of whether the screen /// is active, hidden, or in the middle of a transition. /// </summary> public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (isExiting) { // If the screen is going away to die, it should transition off. screenState = ScreenState.TransitionOff; if (!UpdateTransition(gameTime, transitionOffTime, 1)) { // When the transition finishes, remove the screen. ScreenManager.RemoveScreen(this); } } else if (coveredByOtherScreen) { // If the screen is covered by another, it should transition off. if (UpdateTransition(gameTime, transitionOffTime, 1)) { // Still busy transitioning. screenState = ScreenState.TransitionOff; } else { // Transition finished! screenState = ScreenState.Hidden; } } else { // Otherwise the screen should transition on and become active. if (UpdateTransition(gameTime, transitionOnTime, -1)) { // Still busy transitioning. screenState = ScreenState.TransitionOn; } else { // Transition finished! screenState = ScreenState.Active; } } } /// <summary> /// Helper for updating the screen transition position. /// </summary> bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction) { // How much should we move by? float transitionDelta; if (time == TimeSpan.Zero) transitionDelta = 1; else transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds); // Update the transition position. transitionPosition += transitionDelta * direction; // Did we reach the end of the transition? if (((direction < 0) && (transitionPosition <= 0)) || ((direction > 0) && (transitionPosition >= 1))) { transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1); return false; } // Otherwise we are still busy transitioning. return true; } /// <summary> /// Allows the screen to handle user input. Unlike Update, this method /// is only called when the screen is active, and not when some other /// screen has taken the focus. /// </summary> public virtual void HandleInput(InputState input) { } public KeyboardState currentKeyState; public KeyboardState lastKeyState; public bool IsKeyHit(Keys key) { if (currentKeyState.IsKeyDown(key) && lastKeyState.IsKeyUp(key)) return true; return false; } /// <summary> /// This is called when the screen should draw itself. /// </summary> public virtual void Draw(GameTime gameTime) { } #endregion #region Public Methods /// <summary> /// Tells the screen to serialize its state into the given stream. /// </summary> public virtual void Serialize(Stream stream) { } /// <summary> /// Tells the screen to deserialize its state from the given stream. /// </summary> public virtual void Deserialize(Stream stream) { } /// <summary> /// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which /// instantly kills the screen, this method respects the transition timings /// and will give the screen a chance to gradually transition off. /// </summary> public void ExitScreen() { if (TransitionOffTime == TimeSpan.Zero) { // If the screen has a zero transition time, remove it immediately. ScreenManager.RemoveScreen(this); } else { // Otherwise flag that it should transition off and then exit. isExiting = true; } } #endregion #region Helper Methods /// <summary> /// A helper method which loads assets using the screen manager's /// associated game content loader. /// </summary> /// <typeparam name="T">Type of asset.</typeparam> /// <param name="assetName">Asset name, relative to the loader root /// directory, and not including the .xnb extension.</param> /// <returns></returns> public T Load<T>(string assetName) { return ScreenManager.Game.Content.Load<T>(assetName); } #endregion } }

    Read the article

  • My sample app is getting crash while registering to Filechangeinfo notification

    - by Solitaire
    public partial class Form1 : Form { [DllImport("coredll.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [DllImport("coredll.dll")] static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("coredll.dll")] public static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); //public struct tagSHCHANGENOTIFYENTRY //{ // [MarshalAs(UnmanagedType.SysUInt)] // public ulong dwEventMask; // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4096)] // public string WatchDir; // [MarshalAs(UnmanagedType.Bool)] // public bool fRecursive; //} //tagSHCHANGENOTIFYENTRY test; //[DllImport("aygshell.dll")] //static extern bool SHChangeNotifyRegister(IntPtr hwnd, ref tagSHCHANGENOTIFYENTRY test); const int GWL_WNDPROC = -4; public delegate int WindProc(IntPtr hWnd, int msg, IntPtr Wparam, IntPtr lparam); static private WindProc SampleProc; IntPtr OldDefProc = IntPtr.Zero; public enum SHCNE : uint { SHCNE_RENAMEITEM = 0x00000001, SHCNE_CREATE = 0x00000002, SHCNE_DELETE = 0x00000004, SHCNE_MKDIR = 0x00000008, SHCNE_RMDIR = 0x00000010, SHCNE_MEDIAINSERTED = 0x00000020, SHCNE_MEDIAREMOVED = 0x00000040, SHCNE_DRIVEREMOVED = 0x00000080, SHCNE_DRIVEADD = 0x00000100, SHCNE_NETSHARE = 0x00000200, SHCNE_NETUNSHARE = 0x00000400, SHCNE_ATTRIBUTES = 0x00000800, SHCNE_UPDATEDIR = 0x00001000, SHCNE_UPDATEITEM = 0x00002000, SHCNE_SERVERDISCONNECT = 0x00004000, SHCNE_UPDATEIMAGE = 0x00008000, SHCNE_DRIVEADDGUI = 0x00010000, SHCNE_RENAMEFOLDER = 0x00020000, SHCNE_FREESPACE = 0x00040000, SHCNE_EXTENDED_EVENT = 0x04000000, SHCNE_ASSOCCHANGED = 0x08000000, SHCNE_DISKEVENTS = 0x0002381F, SHCNE_GLOBALEVENTS = 0x0C0581E0, SHCNE_ALLEVENTS = 0x7FFFFFFF, SHCNE_INTERRUPT = 0x80000000, } public enum SHCNF { SHCNF_IDLIST = 0x0000, SHCNF_PATHA = 0x0001, SHCNF_PRINTERA = 0x0002, SHCNF_DWORD = 0x0003, SHCNF_PATHW = 0x0005, SHCNF_PRINTERW = 0x0006, SHCNF_TYPE = 0x00FF, SHCNF_FLUSH = 0x1000, SHCNF_FLUSHNOWAIT = 0x2000 } public const uint WM_SHNOTIFY = 0x0401; private const int WM_FILECHANGEINFO = (0x8000 + 0x101); public struct SHChangeNotifyEntry { public IntPtr pIdl; [MarshalAs(UnmanagedType.Bool)] public Boolean Recursively; } [DllImport("coredll.dll", EntryPoint = "#2", CharSet = CharSet.Auto)] private static extern uint SHChangeNotifyRegister( IntPtr hWnd, SHCNF fSources, SHCNE fEvents, uint wMsg, int cEntries, ref SHChangeNotifyEntry pFsne); [DllImport("Ceshell.dll", CharSet = CharSet.Auto)] private static extern uint SHGetSpecialFolderLocation( IntPtr hWnd, CSIDL nFolder, out IntPtr Pidl); public enum CSIDL { /// <summary> /// Desktop /// </summary> CSIDL_DESKTOP = 0x0000, /// <summary> /// Internet Explorer (icon on desktop) /// </summary> CSIDL_INTERNET = 0x0001, /// <summary> /// Start Menu\Programs /// </summary> CSIDL_PROGRAMS = 0x0002, /// <summary> /// My Computer\Control Panel /// </summary> CSIDL_CONTROLS = 0x0003, /// <summary> /// My Computer\Printers /// </summary> CSIDL_PRINTERS = 0x0004, /// <summary> /// My Documents /// </summary> CSIDL_PERSONAL = 0x0005, /// <summary> /// user name\Favorites /// </summary> CSIDL_FAVORITES = 0x0006, /// <summary> /// Start Menu\Programs\Startup /// </summary> CSIDL_STARTUP = 0x0007, /// <summary> /// user name\Recent /// </summary> CSIDL_RECENT = 0x0008, /// <summary> /// user name\SendTo /// </summary> CSIDL_SENDTO = 0x0009, /// <summary> /// desktop\Recycle Bin /// </summary> CSIDL_BITBUCKET = 0x000a, /// <summary> /// user name\Start Menu /// </summary> CSIDL_STARTMENU = 0x000b, /// <summary> /// logical "My Documents" desktop icon /// </summary> CSIDL_MYDOCUMENTS = 0x000c, /// <summary> /// "My Music" folder /// </summary> CSIDL_MYMUSIC = 0x000d, /// <summary> /// "My Videos" folder /// </summary> CSIDL_MYVIDEO = 0x000e, /// <summary> /// user name\Desktop /// </summary> CSIDL_DESKTOPDIRECTORY = 0x0010, /// <summary> /// My Computer /// </summary> CSIDL_DRIVES = 0x0011, /// <summary> /// Network Neighborhood (My Network Places) /// </summary> CSIDL_NETWORK = 0x0012, /// <summary> /// user name>nethood /// </summary> CSIDL_NETHOOD = 0x0013, /// <summary> /// windows\fonts /// </summary> CSIDL_FONTS = 0x0014, CSIDL_TEMPLATES = 0x0015, /// <summary> /// All Users\Start Menu /// </summary> CSIDL_COMMON_STARTMENU = 0x0016, /// <summary> /// All Users\Start Menu\Programs /// </summary> CSIDL_COMMON_PROGRAMS = 0X0017, /// <summary> /// All Users\Startup /// </summary> CSIDL_COMMON_STARTUP = 0x0018, /// <summary> /// All Users\Desktop /// </summary> CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019, /// <summary> /// user name\Application Data /// </summary> CSIDL_APPDATA = 0x001a, /// <summary> /// user name\PrintHood /// </summary> CSIDL_PRINTHOOD = 0x001b, /// <summary> /// user name\Local Settings\Applicaiton Data (non roaming) /// </summary> CSIDL_LOCAL_APPDATA = 0x001c, /// <summary> /// non localized startup /// </summary> CSIDL_ALTSTARTUP = 0x001d, /// <summary> /// non localized common startup /// </summary> CSIDL_COMMON_ALTSTARTUP = 0x001e, CSIDL_COMMON_FAVORITES = 0x001f, CSIDL_INTERNET_CACHE = 0x0020, CSIDL_COOKIES = 0x0021, CSIDL_HISTORY = 0x0022, /// <summary> /// All Users\Application Data /// </summary> CSIDL_COMMON_APPDATA = 0x0023, /// <summary> /// GetWindowsDirectory() /// </summary> CSIDL_WINDOWS = 0x0024, /// <summary> /// GetSystemDirectory() /// </summary> CSIDL_SYSTEM = 0x0025, /// <summary> /// C:\Program Files /// </summary> CSIDL_PROGRAM_FILES = 0x0026, /// <summary> /// C:\Program Files\My Pictures /// </summary> CSIDL_MYPICTURES = 0x0027, /// <summary> /// USERPROFILE /// </summary> CSIDL_PROFILE = 0x0028, /// <summary> /// x86 system directory on RISC /// </summary> CSIDL_SYSTEMX86 = 0x0029, /// <summary> /// x86 C:\Program Files on RISC /// </summary> CSIDL_PROGRAM_FILESX86 = 0x002a, /// <summary> /// C:\Program Files\Common /// </summary> CSIDL_PROGRAM_FILES_COMMON = 0x002b, /// <summary> /// x86 Program Files\Common on RISC /// </summary> CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c, /// <summary> /// All Users\Templates /// </summary> CSIDL_COMMON_TEMPLATES = 0x002d, /// <summary> /// All Users\Documents /// </summary> CSIDL_COMMON_DOCUMENTS = 0x002e, /// <summary> /// All Users\Start Menu\Programs\Administrative Tools /// </summary> CSIDL_COMMON_ADMINTOOLS = 0x002f, /// <summary> /// user name\Start Menu\Programs\Administrative Tools /// </summary> CSIDL_ADMINTOOLS = 0x0030, /// <summary> /// Network and Dial-up Connections /// </summary> CSIDL_CONNECTIONS = 0x0031, /// <summary> /// All Users\My Music /// </summary> CSIDL_COMMON_MUSIC = 0x0035, /// <summary> /// All Users\My Pictures /// </summary> CSIDL_COMMON_PICTURES = 0x0036, /// <summary> /// All Users\My Video /// </summary> CSIDL_COMMON_VIDEO = 0x0037, /// <summary> /// Resource Direcotry /// </summary> CSIDL_RESOURCES = 0x0038, /// <summary> /// Localized Resource Direcotry /// </summary> CSIDL_RESOURCES_LOCALIZED = 0x0039, /// <summary> /// Links to All Users OEM specific apps /// </summary> CSIDL_COMMON_OEM_LINKS = 0x003a, /// <summary> /// USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning /// </summary> CSIDL_CDBURN_AREA = 0x003b, /// <summary> /// Computers Near Me (computered from Workgroup membership) /// </summary> CSIDL_COMPUTERSNEARME = 0x003d, /// <summary> /// combine with CSIDL_ value to force folder creation in SHGetFolderPath() /// </summary> CSIDL_FLAG_CREATE = 0x8000, /// <summary> /// combine with CSIDL_ value to return an unverified folder path /// </summary> CSIDL_FLAG_DONT_VERIFY = 0x4000, /// <summary> /// combine with CSIDL_ value to insure non-alias versions of the pidl /// </summary> CSIDL_FLAG_NO_ALIAS = 0x1000, /// <summary> /// combine with CSIDL_ value to indicate per-user init (eg. upgrade) /// </summary> CSIDL_FLAG_PER_USER_INIT = 0x0800, /// <summary> /// mask for all possible /// </summary> CSIDL_FLAG_MASK = 0xFF00, } public enum SHGetFolderLocationReturnValues : uint { /// <summary> /// Success /// </summary> S_OK = 0x00000000, /// <summary> /// The CSIDL in nFolder is valid but the folder does not exist /// </summary> S_FALSE = 0x00000001, /// <summary> /// The CSIDL in nFolder is not valid /// </summary> E_INVALIDARG = 0x80070057 } public static IntPtr GetPidlFromFolderID(IntPtr hWnd, CSIDL Id) { IntPtr pIdl = IntPtr.Zero; SHGetFolderLocationReturnValues res = (SHGetFolderLocationReturnValues) SHGetSpecialFolderLocation( hWnd, Id, out pIdl); return (pIdl); } public Form1() { InitializeComponent(); SampleProc = new WindProc (SubclassWndProc); OldDefProc = GetWindowLong(this.Handle, GWL_WNDPROC); SetWindowLong(this.Handle, GWL_WNDPROC, Marshal.GetFunctionPointerForDelegate(SampleProc)/*SampleProc.Method.MethodHandle.Value.ToInt32()*/); //tagSHCHANGENOTIFYENTRY changeentry = new tagSHCHANGENOTIFYENTRY(); //changeentry.dwEventMask = (ulong)SHCNE.SHCNE_ALLEVENTS; //changeentry.fRecursive = true; //changeentry.WatchDir = null; //SHChangeNotifyRegister(this.Handle, ref changeentry); SHChangeNotifyEntry changeentry = new SHChangeNotifyEntry(); changeentry.pIdl = GetPidlFromFolderID(this.Handle, CSIDL.CSIDL_DESKTOP); changeentry.Recursively = true; try { uint notifyid = SHChangeNotifyRegister( this.Handle, SHCNF.SHCNF_TYPE | SHCNF.SHCNF_IDLIST, SHCNE.SHCNE_ALLEVENTS, WM_FILECHANGEINFO, 1, ref changeentry); } catch (Exception ee) { } i am failing in SHChangeNotifyRegister please help me.. tell me the reason why i am crashing..same code work fine for desktop.. please help Thanks.

    Read the article

  • Creating a new instance, C#

    - by Dave Voyles
    This sounds like a very n00b question, but bear with me here: I'm trying to access the position of my bat (paddle) in my pong game and use it in my ball class. I'm doing this because I want a particle effect to go off at the point of contact where the ball hits the bat. Each time the ball hits the bat, I receive an error stating that I haven't created an instance of the bat. I understand that I have to (or can use a static class), but I'm not sure of how to do so in this example. I've included both my Bat and Ball classes. namespace Pong { #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion public class Ball { #region Fields private readonly Random rand; private readonly Texture2D texture; private readonly SoundEffect warp; private double direction; private bool isVisible; private float moveSpeed; private Vector2 position; private Vector2 resetPos; private Rectangle size; private float speed; private bool isResetting; private bool collided; private Vector2 oldPos; private ParticleEngine particleEngine; private ContentManager contentManager; private SpriteBatch spriteBatch; private bool hasHitBat; private AIBat aiBat; private Bat bat; #endregion #region Constructors and Destructors /// <summary> /// Constructor for the ball /// </summary> public Ball(ContentManager contentManager, Vector2 ScreenSize) { moveSpeed = 15f; speed = 0; texture = contentManager.Load<Texture2D>(@"gfx/balls/redBall"); direction = 0; size = new Rectangle(0, 0, texture.Width, texture.Height); resetPos = new Vector2(ScreenSize.X / 2, ScreenSize.Y / 2); position = resetPos; rand = new Random(); isVisible = true; hasHitBat = false; // Everything to do with particles List<Texture2D> textures = new List<Texture2D>(); textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/circle")); textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/star")); textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/diamond")); particleEngine = new ParticleEngine(textures, new Vector2()); } #endregion #region Public Methods and Operators /// <summary> /// Checks for the collision between the bat and the ball. Sends ball in the appropriate /// direction /// </summary> public void BatHit(int block) { if (direction > Math.PI * 1.5f || direction < Math.PI * 0.5f) { hasHitBat = true; particleEngine.EmitterLocation = new Vector2(aiBat.Position.X, aiBat.Position.Y); switch (block) { case 1: direction = MathHelper.ToRadians(200); break; case 2: direction = MathHelper.ToRadians(195); break; case 3: direction = MathHelper.ToRadians(180); break; case 4: direction = MathHelper.ToRadians(180); break; case 5: direction = MathHelper.ToRadians(165); break; } } else { hasHitBat = true; particleEngine.EmitterLocation = new Vector2(bat.Position.X, bat.Position.Y); switch (block) { case 1: direction = MathHelper.ToRadians(310); break; case 2: direction = MathHelper.ToRadians(345); break; case 3: direction = MathHelper.ToRadians(0); break; case 4: direction = MathHelper.ToRadians(15); break; case 5: direction = MathHelper.ToRadians(50); break; } } if (rand.Next(2) == 0) { direction += MathHelper.ToRadians(rand.Next(3)); } else { direction -= MathHelper.ToRadians(rand.Next(3)); } AudioManager.Instance.PlaySoundEffect("hit"); } /// <summary> /// JEP - added method to slow down ball after powerup deactivates /// </summary> public void DecreaseSpeed() { moveSpeed -= 0.6f; } /// <summary> /// Draws the ball on the screen /// </summary> public void Draw(SpriteBatch spriteBatch) { if (isVisible) { spriteBatch.Begin(); spriteBatch.Draw(texture, size, Color.White); spriteBatch.End(); // Draws sprites for particles when contact is made particleEngine.Draw(spriteBatch); } } /// <summary> /// Checks for the current direction of the ball /// </summary> public double GetDirection() { return direction; } /// <summary> /// Checks for the current position of the ball /// </summary> public Vector2 GetPosition() { return position; } /// <summary> /// Checks for the current size of the ball (for the powerups) /// </summary> public Rectangle GetSize() { return size; } /// <summary> /// Grows the size of the ball when the GrowBall powerup is used. /// </summary> public void GrowBall() { size = new Rectangle(0, 0, texture.Width * 2, texture.Height * 2); } /// <summary> /// Was used to increased the speed of the ball after each point is scored. /// No longer used, but am considering implementing again. /// </summary> public void IncreaseSpeed() { moveSpeed += 0.6f; } /// <summary> /// Check for the ball to return normal size after the Powerup has expired /// </summary> public void NormalBallSize() { size = new Rectangle(0, 0, texture.Width, texture.Height); } /// <summary> /// Check for the ball to return normal speed after the Powerup has expired /// </summary> public void NormalSpeed() { moveSpeed += 15f; } /// <summary> /// Checks to see if ball went out of bounds, and triggers warp sfx /// </summary> public void OutOfBounds() { // Checks if the player is still alive or not if (isResetting) { AudioManager.Instance.PlaySoundEffect("warp"); { // Used to stop the the issue where the ball hit sfx kept going off when detecting collison isResetting = false; AudioManager.Instance.Dispose(); } } } /// <summary> /// Speed for the ball when Speedball powerup is activated /// </summary> public void PowerupSpeed() { moveSpeed += 20.0f; } /// <summary> /// Check for where to reset the ball after each point is scored /// </summary> public void Reset(bool left) { if (left) { direction = 0; } else { direction = Math.PI; } // Used to stop the the issue where the ball hit sfx kept going off when detecting collison isResetting = true; position = resetPos; // Resets the ball to the center of the screen isVisible = true; speed = 15f; // Returns the ball back to the default speed, in case the speedBall was active if (rand.Next(2) == 0) { direction += MathHelper.ToRadians(rand.Next(30)); } else { direction -= MathHelper.ToRadians(rand.Next(30)); } } /// <summary> /// Shrinks the ball when the ShrinkBall powerup is activated /// </summary> public void ShrinkBall() { size = new Rectangle(0, 0, texture.Width / 2, texture.Height / 2); } /// <summary> /// Stops the ball each time it is reset. Ex: Between points / rounds /// </summary> public void Stop() { isVisible = true; speed = 0; } /// <summary> /// Updates position of the ball /// </summary> public void UpdatePosition() { size.X = (int)position.X; size.Y = (int)position.Y; oldPos.X = position.X; oldPos.Y = position.Y; position.X += speed * (float)Math.Cos(direction); position.Y += speed * (float)Math.Sin(direction); bool collided = CheckWallHit(); particleEngine.Update(); // Stops the issue where ball was oscillating on the ceiling or floor if (collided) { position.X = oldPos.X + speed * (float)Math.Cos(direction); position.Y = oldPos.Y + speed * (float)Math.Sin(direction); } } #endregion #region Methods /// <summary> /// Checks for collision with the ceiling or floor. 2*Math.pi = 360 degrees /// </summary> private bool CheckWallHit() { while (direction > 2 * Math.PI) { direction -= 2 * Math.PI; return true; } while (direction < 0) { direction += 2 * Math.PI; return true; } if (position.Y <= 0 || (position.Y > resetPos.Y * 2 - size.Height)) { direction = 2 * Math.PI - direction; return true; } return true; } #endregion } } namespace Pong { using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; public class Bat { public Vector2 Position; public float moveSpeed; public Rectangle size; private int points; private int yHeight; private Texture2D leftBat; public float turbo; public float recharge; public float interval; public bool isTurbo; /// <summary> /// Constructor for the bat /// </summary> public Bat(ContentManager contentManager, Vector2 screenSize, bool side) { moveSpeed = 7f; turbo = 15f; recharge = 100f; points = 0; interval = 5f; leftBat = contentManager.Load<Texture2D>(@"gfx/bats/batGrey"); size = new Rectangle(0, 0, leftBat.Width, leftBat.Height); // True means left bat, false means right bat. if (side) Position = new Vector2(30, screenSize.Y / 2 - size.Height / 2); else Position = new Vector2(screenSize.X - 30, screenSize.Y / 2 - size.Height / 2); yHeight = (int)screenSize.Y; } public void IncreaseSpeed() { moveSpeed += .5f; } /// <summary> /// The speed of the bat when Turbo is activated /// </summary> public void Turbo() { moveSpeed += 8.0f; } /// <summary> /// Returns the speed of the bat back to normal after Turbo is deactivated /// </summary> public void DisableTurbo() { moveSpeed = 7.0f; isTurbo = false; } /// <summary> /// Returns the bat to the nrmal size after the Grow/Shrink powerup has expired /// </summary> public void NormalSize() { size = new Rectangle(0, 0, leftBat.Width, leftBat.Height); } /// <summary> /// Checks for the size of the bat /// </summary> public Rectangle GetSize() { return size; } /// <summary> /// Adds point to the player or the AI after scoring. Currently Disabled. /// </summary> public void IncrementPoints() { points++; } /// <summary> /// Checks for the number of points at the moment /// </summary> public int GetPoints() { return points; } /// <summary> /// Sets thedefault starting position for the bats /// </summary> /// <param name="position"></param> public void SetPosition(Vector2 position) { if (position.Y < 0) { position.Y = 0; } if (position.Y > yHeight - size.Height) { position.Y = yHeight - size.Height; } this.Position = position; } /// <summary> /// Checks for the current position of the bat /// </summary> public Vector2 GetPosition() { return Position; } /// <summary> /// Controls the bat moving up the screen /// </summary> public void MoveUp() { SetPosition(Position + new Vector2(0, -moveSpeed)); } /// <summary> /// Controls the bat moving down the screen /// </summary> public void MoveDown() { SetPosition(Position + new Vector2(0, moveSpeed)); } /// <summary> /// Updates the position of the AI bat, in order to track the ball /// </summary> /// <param name="ball"></param> public virtual void UpdatePosition(Ball ball) { size.X = (int)Position.X; size.Y = (int)Position.Y; } /// <summary> /// Resets the bat to the center location after a new game starts /// </summary> public void ResetPosition() { SetPosition(new Vector2(GetPosition().X, yHeight / 2 - size.Height)); } /// <summary> /// Used for the Growbat powerup /// </summary> public void GrowBat() { // Doubles the size of the bat collision size = new Rectangle(0, 0, leftBat.Width * 2, leftBat.Height * 2); } /// <summary> /// Used for the Shrinkbat powerup /// </summary> public void ShrinkBat() { // 1/2 the size of the bat collision size = new Rectangle(0, 0, leftBat.Width / 2, leftBat.Height / 2); } /// <summary> /// Draws the bats /// </summary> public virtual void Draw(SpriteBatch batch) { batch.Draw(leftBat, size, Color.White); } } }

    Read the article

  • Getting a summary of comments in Jira

    - by Ross Alexander
    I currently maintain a Jira system at work and I have been tasked with a rather strange request which is too find a way of 'making a summary of a comment'. In the ideal situation this would allow a user to write a comment and a quick summary however I doubt this is something available in Jira / something that is feasible. Alternatively a summary of all comments would be nice that will allow our technical writers a way to clarify fixes through the information in the comments. If any one out there has ANY suggestions or ideas on this they are most welcome :) Sorry if this question is slightly general but I cannot find any thing that remotely helps on google, wondering if any Jira experts can push me in the right direction. Thanks

    Read the article

  • C# XNA Handle mouse events?

    - by user406470
    I'm making a 2D game engine called Clixel over on GitHub. The problem I have relates to two classes, ClxMouse and ClxButton. In it I have a mouse class - the code for that can be viewed here. ClxMouse using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace org.clixel { public class ClxMouse : ClxSprite { private MouseState _curmouse, _lastmouse; public int Sensitivity = 3; public bool Lock = true; public Vector2 Change { get { return new Vector2(_curmouse.X - _lastmouse.X, _curmouse.Y - _lastmouse.Y); } } private int _scrollwheel; public int ScrollWheel { get { return _scrollwheel; } } public bool LeftDown { get { if (_curmouse.LeftButton == ButtonState.Pressed) return true; else return false; } } public bool RightDown { get { if (_curmouse.RightButton == ButtonState.Pressed) return true; else return false; } } public bool MiddleDown { get { if (_curmouse.MiddleButton == ButtonState.Pressed) return true; else return false; } } public bool LeftPressed { get { if (_curmouse.LeftButton == ButtonState.Pressed && _lastmouse.LeftButton == ButtonState.Released) return true; else return false; } } public bool RightPressed { get { if (_curmouse.RightButton == ButtonState.Pressed && _lastmouse.RightButton == ButtonState.Released) return true; else return false; } } public bool MiddlePressed { get { if (_curmouse.MiddleButton == ButtonState.Pressed && _lastmouse.MiddleButton == ButtonState.Released) return true; else return false; } } public bool LeftReleased { get { if (_curmouse.LeftButton == ButtonState.Released && _lastmouse.LeftButton == ButtonState.Pressed) return true; else return false; } } public bool RightReleased { get { if (_curmouse.RightButton == ButtonState.Released && _lastmouse.RightButton == ButtonState.Pressed) return true; else return false; } } public bool MiddleReleased { get { if (_curmouse.MiddleButton == ButtonState.Released && _lastmouse.MiddleButton == ButtonState.Pressed) return true; else return false; } } public MouseState CurMouse { get { return _curmouse; } } public MouseState LastMouse { get { return _lastmouse; } } public ClxMouse() : base(ClxG.Textures.Default.Cursor) { _curmouse = Mouse.GetState(); _lastmouse = _curmouse; CollisionBox = new Rectangle(ClxG.Screen.Center.X, ClxG.Screen.Center.Y, Texture.Width, Texture.Height); this.Solid = false; DefaultPosition = new Vector2(CollisionBox.X, CollisionBox.Y); Mouse.SetPosition(CollisionBox.X, CollisionBox.Y); } public ClxMouse(Texture2D _texture) : base(_texture) { _curmouse = Mouse.GetState(); _lastmouse = _curmouse; CollisionBox = new Rectangle(ClxG.Screen.Center.X, ClxG.Screen.Center.Y, Texture.Width, Texture.Height); DefaultPosition = new Vector2(CollisionBox.X, CollisionBox.Y); } public override void Update() { _lastmouse = _curmouse; _curmouse = Mouse.GetState(); if (_curmouse != _lastmouse) { if (ClxG.Game.IsActive) { _scrollwheel = _curmouse.ScrollWheelValue; Velocity = new Vector2(Change.X / Sensitivity, Change.Y / Sensitivity); if (Lock) Mouse.SetPosition(ClxG.Screen.Center.X, ClxG.Screen.Center.Y); _curmouse = Mouse.GetState(); } base.Update(); } } public override void Draw(SpriteBatch _sb) { base.Draw(_sb); } } } ClxButton using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace org.clixel { public class ClxButton : ClxSprite { /// <summary> /// The color when the mouse is over the button /// </summary> public Color HoverColor; /// <summary> /// The color when the color is being clicked /// </summary> public Color ClickColor; /// <summary> /// The color when the button is inactive /// </summary> public Color InactiveColor; /// <summary> /// The color when the button is active /// </summary> public Color ActiveColor; /// <summary> /// The color after the button has been clicked. /// </summary> public Color ClickedColor; /// <summary> /// The text to be displayed on the button, set to "" if no text is needed. /// </summary> public string Text; /// <summary> /// The ClxText object to be displayed. /// </summary> public ClxText TextRender; /// <summary> /// The ClxState that should be ResetAndShow() when the button is clicked. /// </summary> public ClxState ClickState; /// <summary> /// Collision check to make sure onCollide() only runs once per frame, /// since only the mouse needs to be collision checked. /// </summary> private bool _runonce = false; /// <summary> /// Gets a value indicating whether this instance is colliding. /// </summary> /// <value> /// <c>true</c> if this instance is colliding; otherwise, <c>false</c>. /// </value> public bool IsColliding { get { return _runonce; } } /// <summary> /// Initializes a new instance of the <see cref="ClxButton"/> class. /// </summary> public ClxButton() : base(ClxG.Textures.Default.Button) { HoverColor = Color.Red; ClickColor = Color.Blue; InactiveColor = Color.Gray; ActiveColor = Color.White; ClickedColor = Color.Yellow; Text = Name + ID + " Unset!"; TextRender = new ClxText(); TextRender.Text = Text; TextRender.TextPadding = new Vector2(5, 5); ClickState = null; CollideObjects(ClxG.Mouse); } /// <summary> /// Initializes a new instance of the <see cref="ClxButton"/> class. /// </summary> /// <param name="_texture">The button texture.</param> public ClxButton(Texture2D _texture) : base(_texture) { HoverColor = Color.Red; ClickColor = Color.Blue; InactiveColor = Color.Gray; ActiveColor = Color.White; ClickedColor = Color.Yellow; Texture = _texture; Text = Name + ID; TextRender = new ClxText(); TextRender.Name = this.Name + ".TextRender"; TextRender.Text = Text; TextRender.TextPadding = new Vector2(5, 5); TextRender.Reset(); ClickState = null; CollideObjects(ClxG.Mouse); } /// <summary> /// Draws the debug information, run from ClxG.DrawDebug unless manual control is assumed. /// </summary> /// <param name="_sb">SpriteBatch used for drawing.</param> public override void DrawDebug(SpriteBatch _sb) { _runonce = false; TextRender.DrawDebug(_sb); _sb.Draw(Texture, ActualRectangle, new Rectangle(0, 0, Texture.Width, Texture.Height), DebugColor, Rotation, Origin, Flip, Layer); _sb.Draw(ClxG.Textures.Default.DebugBG, new Rectangle(ActualRectangle.X - DebugLineWidth, ActualRectangle.Y - DebugLineWidth, ActualRectangle.Width + DebugLineWidth * 2, ActualRectangle.Height + DebugLineWidth * 2), new Rectangle(0, 0, ClxG.Textures.Default.DebugBG.Width, ClxG.Textures.Default.DebugBG.Height), DebugOutline, Rotation, Origin, Flip, Layer - 0.1f); _sb.Draw(ClxG.Textures.Default.DebugBG, ActualRectangle, new Rectangle(0, 0, ClxG.Textures.Default.DebugBG.Width, ClxG.Textures.Default.DebugBG.Height), DebugBGColor, Rotation, Origin, Flip, Layer - 0.01f); } /// <summary> /// Draws using the SpriteBatch, run from ClxG.Draw unless manual control is assumed. /// </summary> /// <param name="_sb">SpriteBatch used for drawing.</param> public override void Draw(SpriteBatch _sb) { _runonce = false; TextRender.Draw(_sb); if (Visible) if (Debug) { DrawDebug(_sb); } else _sb.Draw(Texture, ActualRectangle, new Rectangle(0, 0, Texture.Width, Texture.Height), Color, Rotation, Origin, Flip, Layer); } /// <summary> /// Updates this instance. /// </summary> public override void Update() { if (this.Color != ActiveColor) this.Color = ActiveColor; TextRender.Layer = this.Layer + 0.03f; TextRender.Text = Text; TextRender.Scale = .5f; TextRender.Name = this.Name + ".TextRender"; TextRender.Origin = new Vector2(TextRender.CollisionBox.Center.X, TextRender.CollisionBox.Center.Y); TextRender.Center(this); TextRender.Update(); this.CollisionBox.Width = (int)(TextRender.CollisionBox.Width * TextRender.Scale) + (int)(TextRender.TextPadding.X * 2); this.CollisionBox.Height = (int)(TextRender.CollisionBox.Height * TextRender.Scale) + (int)(TextRender.TextPadding.Y * 2); base.Update(); } /// <summary> /// Collide event, takes the colliding object to call it's proper collision code. /// You'd want to use something like if(typeof(collider) == typeof(ClxObject) /// </summary> /// <param name="collider">The colliding object.</param> public override void onCollide(ClxObject collider) { if (!_runonce) { _runonce = true; UpdateEvents(); base.onCollide(collider); } } /// <summary> /// Updates the mouse based events. /// </summary> public void UpdateEvents() { onHover(); if (ClxG.Mouse.LeftReleased) { onLeftReleased(); return; } if (ClxG.Mouse.RightReleased) { onRightReleased(); return; } if (ClxG.Mouse.MiddleReleased) { onMiddleReleased(); return; } if (ClxG.Mouse.LeftPressed) { onLeftClicked(); return; } if (ClxG.Mouse.RightPressed) { onRightClicked(); return; } if (ClxG.Mouse.MiddlePressed) { onMiddleClicked(); return; } if (ClxG.Mouse.LeftDown) { onLeftClick(); return; } if (ClxG.Mouse.RightDown) { onRightClick(); return; } if (ClxG.Mouse.MiddleDown) { onMiddleClick(); return; } } /// <summary> /// Shows the state of the click. /// </summary> public void ShowClickState() { if (ClickState != null) { ClickState.ResetAndShow(); } } /// <summary> /// Hover event /// </summary> virtual public void onHover() { this.Color = HoverColor; } /// <summary> /// Left click event /// </summary> virtual public void onLeftClick() { this.Color = ClickColor; } /// <summary> /// Right click event /// </summary> virtual public void onRightClick() { } /// <summary> /// Middle click event /// </summary> virtual public void onMiddleClick() { } /// <summary> /// Left click event, called once per click /// </summary> virtual public void onLeftClicked() { ShowClickState(); } /// <summary> /// Right click event, called once per click /// </summary> virtual public void onRightClicked() { this.Reset(); } /// <summary> /// Middle click event, called once per click /// </summary> virtual public void onMiddleClicked() { } /// <summary> /// Ons the left released. /// </summary> virtual public void onLeftReleased() { this.Color = ClickedColor; } virtual public void onRightReleased() { } virtual public void onMiddleReleased() { } } } The issue I have is that I have all these have event styled methods, especially in ClxButton with all the onLeftClick, onRightClick, etc, etc. Is there a better way for me to handle these events to be a lot more easier for a programmer to use? I was looking at normal events on some other sites, (I'd post them but I need more rep.) and didn't really see a good way to implement delegate events into my framework. I'm not really sure how these events work, could someone possibly lay out how these events are processed for me? TL:DR * Is there a better way to handle events like this? * Are events a viable solution to this problem? Thanks in advance for any help.

    Read the article

  • javascript summary function

    - by Phil Jackson
    Hello, im trying to make a small name summary function depending on the size of the elements container, here's what I have; function shorten_text(str, size){ size = size.match( /[0-9]*/ ); var endValue = Math.floor( Number(size) / 10 ); var number; var newStr; for ( number = 0; number <= endValue; number++ ) { if( str[number].length != 0 ) { newStr += str[number]; } } return newStr + '...'; } shorten_text('Phil Jackson', '94px'); // output should be 'Phil Jack...' What I seem to get is undefinedundef... can anyone see where I am going wrong?

    Read the article

  • Capturing and Transforming ASP.NET Output with Response.Filter

    - by Rick Strahl
    During one of my Handlers and Modules session at DevConnections this week one of the attendees asked a question that I didn’t have an immediate answer for. Basically he wanted to capture response output completely and then apply some filtering to the output – effectively injecting some additional content into the page AFTER the page had completely rendered. Specifically the output should be captured from anywhere – not just a page and have this code injected into the page. Some time ago I posted some code that allows you to capture ASP.NET Page output by overriding the Render() method, capturing the HtmlTextWriter() and reading its content, modifying the rendered data as text then writing it back out. I’ve actually used this approach on a few occasions and it works fine for ASP.NET pages. But this obviously won’t work outside of the Page class environment and it’s not really generic – you have to create a custom page class in order to handle the output capture. [updated 11/16/2009 – updated ResponseFilterStream implementation and a few additional notes based on comments] Enter Response.Filter However, ASP.NET includes a Response.Filter which can be used – well to filter output. Basically Response.Filter is a stream through which the OutputStream is piped back to the Web Server (indirectly). As content is written into the Response object, the filter stream receives the appropriate Stream commands like Write, Flush and Close as well as read operations although for a Response.Filter that’s uncommon to be hit. The Response.Filter can be programmatically replaced at runtime which allows you to effectively intercept all output generation that runs through ASP.NET. A common Example: Dynamic GZip Encoding A rather common use of Response.Filter hooking up code based, dynamic  GZip compression for requests which is dead simple by applying a GZipStream (or DeflateStream) to Response.Filter. The following generic routines can be used very easily to detect GZip capability of the client and compress response output with a single line of code and a couple of library helper routines: WebUtils.GZipEncodePage(); which is handled with a few lines of reusable code and a couple of static helper methods: /// <summary> ///Sets up the current page or handler to use GZip through a Response.Filter ///IMPORTANT:  ///You have to call this method before any output is generated! /// </summary> public static void GZipEncodePage() {     HttpResponse Response = HttpContext.Current.Response;     if(IsGZipSupported())     {         stringAcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];         if(AcceptEncoding.Contains("deflate"))         {             Response.Filter = newSystem.IO.Compression.DeflateStream(Response.Filter,                                        System.IO.Compression.CompressionMode.Compress);             Response.AppendHeader("Content-Encoding", "deflate");         }         else        {             Response.Filter = newSystem.IO.Compression.GZipStream(Response.Filter,                                       System.IO.Compression.CompressionMode.Compress);             Response.AppendHeader("Content-Encoding", "gzip");                            }     }     // Allow proxy servers to cache encoded and unencoded versions separately    Response.AppendHeader("Vary", "Content-Encoding"); } /// <summary> /// Determines if GZip is supported /// </summary> /// <returns></returns> public static bool IsGZipSupported() { string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))) return true; return false; } GZipStream and DeflateStream are streams that are assigned to Response.Filter and by doing so apply the appropriate compression on the active Response. Response.Filter content is chunked So to implement a Response.Filter effectively requires only that you implement a custom stream and handle the Write() method to capture Response output as it’s written. At first blush this seems very simple – you capture the output in Write, transform it and write out the transformed content in one pass. And that indeed works for small amounts of content. But you see, the problem is that output is written in small buffer chunks (a little less than 16k it appears) rather than just a single Write() statement into the stream, which makes perfect sense for ASP.NET to stream data back to IIS in smaller chunks to minimize memory usage en route. Unfortunately this also makes it a more difficult to implement any filtering routines since you don’t directly get access to all of the response content which is problematic especially if those filtering routines require you to look at the ENTIRE response in order to transform or capture the output as is needed for the solution the gentleman in my session asked for. So in order to address this a slightly different approach is required that basically captures all the Write() buffers passed into a cached stream and then making the stream available only when it’s complete and ready to be flushed. As I was thinking about the implementation I also started thinking about the few instances when I’ve used Response.Filter implementations. Each time I had to create a new Stream subclass and create my custom functionality but in the end each implementation did the same thing – capturing output and transforming it. I thought there should be an easier way to do this by creating a re-usable Stream class that can handle stream transformations that are common to Response.Filter implementations. Creating a semi-generic Response Filter Stream Class What I ended up with is a ResponseFilterStream class that provides a handful of Events that allow you to capture and/or transform Response content. The class implements a subclass of Stream and then overrides Write() and Flush() to handle capturing and transformation operations. By exposing events it’s easy to hook up capture or transformation operations via single focused methods. ResponseFilterStream exposes the following events: CaptureStream, CaptureString Captures the output only and provides either a MemoryStream or String with the final page output. Capture is hooked to the Flush() operation of the stream. TransformStream, TransformString Allows you to transform the complete response output with events that receive a MemoryStream or String respectively and can you modify the output then return it back as a return value. The transformed output is then written back out in a single chunk to the response output stream. These events capture all output internally first then write the entire buffer into the response. TransformWrite, TransformWriteString Allows you to transform the Response data as it is written in its original chunk size in the Stream’s Write() method. Unlike TransformStream/TransformString which operate on the complete output, these events only see the current chunk of data written. This is more efficient as there’s no caching involved, but can cause problems due to searched content splitting over multiple chunks. Using this implementation, creating a custom Response.Filter transformation becomes as simple as the following code. To hook up the Response.Filter using the MemoryStream version event: ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformStream += filter_TransformStream; Response.Filter = filter; and the event handler to do the transformation: MemoryStream filter_TransformStream(MemoryStream ms) { Encoding encoding = HttpContext.Current.Response.ContentEncoding; string output = encoding.GetString(ms.ToArray()); output = FixPaths(output); ms = new MemoryStream(output.Length); byte[] buffer = encoding.GetBytes(output); ms.Write(buffer,0,buffer.Length); return ms; } private string FixPaths(string output) { string path = HttpContext.Current.Request.ApplicationPath; // override root path wonkiness if (path == "/") path = ""; output = output.Replace("\"~/", "\"" + path + "/").Replace("'~/", "'" + path + "/"); return output; } The idea of the event handler is that you can do whatever you want to the stream and return back a stream – either the same one that’s been modified or a brand new one – which is then sent back to as the final response. The above code can be simplified even more by using the string version events which handle the stream to string conversions for you: ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformString += filter_TransformString; Response.Filter = filter; and the event handler to do the transformation calling the same FixPaths method shown above: string filter_TransformString(string output) { return FixPaths(output); } The events for capturing output and capturing and transforming chunks work in a very similar way. By using events to handle the transformations ResponseFilterStream becomes a reusable component and we don’t have to create a new stream class or subclass an existing Stream based classed. By the way, the example used here is kind of a cool trick which transforms “~/” expressions inside of the final generated HTML output – even in plain HTML controls not HTML controls – and transforms them into the appropriate application relative path in the same way that ResolveUrl would do. So you can write plain old HTML like this: <a href=”~/default.aspx”>Home</a>  and have it turned into: <a href=”/myVirtual/default.aspx”>Home</a>  without having to use an ASP.NET control like Hyperlink or Image or having to constantly use: <img src=”<%= ResolveUrl(“~/images/home.gif”) %>” /> in MVC applications (which frankly is one of the most annoying things about MVC especially given the path hell that extension-less and endpoint-less URLs impose). I can’t take credit for this idea. While discussing the Response.Filter issues on Twitter a hint from Dylan Beattie who pointed me at one of his examples which does something similar. I thought the idea was cool enough to use an example for future demos of Response.Filter functionality in ASP.NET next I time I do the Modules and Handlers talk (which was great fun BTW). How practical this is is debatable however since there’s definitely some overhead to using a Response.Filter in general and especially on one that caches the output and the re-writes it later. Make sure to test for performance anytime you use Response.Filter hookup and make sure it' doesn’t end up killing perf on you. You’ve been warned :-}. How does ResponseFilterStream work? The big win of this implementation IMHO is that it’s a reusable  component – so for implementation there’s no new class, no subclassing – you simply attach to an event to implement an event handler method with a straight forward signature to retrieve the stream or string you’re interested in. The implementation is based on a subclass of Stream as is required in order to handle the Response.Filter requirements. What’s different than other implementations I’ve seen in various places is that it supports capturing output as a whole to allow retrieving the full response output for capture or modification. The exception are the TransformWrite and TransformWrite events which operate only active chunk of data written by the Response. For captured output, the Write() method captures output into an internal MemoryStream that is cached until writing is complete. So Write() is called when ASP.NET writes to the Response stream, but the filter doesn’t pass on the Write immediately to the filter’s internal stream. The data is cached and only when the Flush() method is called to finalize the Stream’s output do we actually send the cached stream off for transformation (if the events are hooked up) and THEN finally write out the returned content in one big chunk. Here’s the implementation of ResponseFilterStream: /// <summary> /// A semi-generic Stream implementation for Response.Filter with /// an event interface for handling Content transformations via /// Stream or String. /// <remarks> /// Use with care for large output as this implementation copies /// the output into a memory stream and so increases memory usage. /// </remarks> /// </summary> public class ResponseFilterStream : Stream { /// <summary> /// The original stream /// </summary> Stream _stream; /// <summary> /// Current position in the original stream /// </summary> long _position; /// <summary> /// Stream that original content is read into /// and then passed to TransformStream function /// </summary> MemoryStream _cacheStream = new MemoryStream(5000); /// <summary> /// Internal pointer that that keeps track of the size /// of the cacheStream /// </summary> int _cachePointer = 0; /// <summary> /// /// </summary> /// <param name="responseStream"></param> public ResponseFilterStream(Stream responseStream) { _stream = responseStream; } /// <summary> /// Determines whether the stream is captured /// </summary> private bool IsCaptured { get { if (CaptureStream != null || CaptureString != null || TransformStream != null || TransformString != null) return true; return false; } } /// <summary> /// Determines whether the Write method is outputting data immediately /// or delaying output until Flush() is fired. /// </summary> private bool IsOutputDelayed { get { if (TransformStream != null || TransformString != null) return true; return false; } } /// <summary> /// Event that captures Response output and makes it available /// as a MemoryStream instance. Output is captured but won't /// affect Response output. /// </summary> public event Action<MemoryStream> CaptureStream; /// <summary> /// Event that captures Response output and makes it available /// as a string. Output is captured but won't affect Response output. /// </summary> public event Action<string> CaptureString; /// <summary> /// Event that allows you transform the stream as each chunk of /// the output is written in the Write() operation of the stream. /// This means that that it's possible/likely that the input /// buffer will not contain the full response output but only /// one of potentially many chunks. /// /// This event is called as part of the filter stream's Write() /// operation. /// </summary> public event Func<byte[], byte[]> TransformWrite; /// <summary> /// Event that allows you to transform the response stream as /// each chunk of bytep[] output is written during the stream's write /// operation. This means it's possibly/likely that the string /// passed to the handler only contains a portion of the full /// output. Typical buffer chunks are around 16k a piece. /// /// This event is called as part of the stream's Write operation. /// </summary> public event Func<string, string> TransformWriteString; /// <summary> /// This event allows capturing and transformation of the entire /// output stream by caching all write operations and delaying final /// response output until Flush() is called on the stream. /// </summary> public event Func<MemoryStream, MemoryStream> TransformStream; /// <summary> /// Event that can be hooked up to handle Response.Filter /// Transformation. Passed a string that you can modify and /// return back as a return value. The modified content /// will become the final output. /// </summary> public event Func<string, string> TransformString; protected virtual void OnCaptureStream(MemoryStream ms) { if (CaptureStream != null) CaptureStream(ms); } private void OnCaptureStringInternal(MemoryStream ms) { if (CaptureString != null) { string content = HttpContext.Current.Response.ContentEncoding.GetString(ms.ToArray()); OnCaptureString(content); } } protected virtual void OnCaptureString(string output) { if (CaptureString != null) CaptureString(output); } protected virtual byte[] OnTransformWrite(byte[] buffer) { if (TransformWrite != null) return TransformWrite(buffer); return buffer; } private byte[] OnTransformWriteStringInternal(byte[] buffer) { Encoding encoding = HttpContext.Current.Response.ContentEncoding; string output = OnTransformWriteString(encoding.GetString(buffer)); return encoding.GetBytes(output); } private string OnTransformWriteString(string value) { if (TransformWriteString != null) return TransformWriteString(value); return value; } protected virtual MemoryStream OnTransformCompleteStream(MemoryStream ms) { if (TransformStream != null) return TransformStream(ms); return ms; } /// <summary> /// Allows transforming of strings /// /// Note this handler is internal and not meant to be overridden /// as the TransformString Event has to be hooked up in order /// for this handler to even fire to avoid the overhead of string /// conversion on every pass through. /// </summary> /// <param name="responseText"></param> /// <returns></returns> private string OnTransformCompleteString(string responseText) { if (TransformString != null) TransformString(responseText); return responseText; } /// <summary> /// Wrapper method form OnTransformString that handles /// stream to string and vice versa conversions /// </summary> /// <param name="ms"></param> /// <returns></returns> internal MemoryStream OnTransformCompleteStringInternal(MemoryStream ms) { if (TransformString == null) return ms; //string content = ms.GetAsString(); string content = HttpContext.Current.Response.ContentEncoding.GetString(ms.ToArray()); content = TransformString(content); byte[] buffer = HttpContext.Current.Response.ContentEncoding.GetBytes(content); ms = new MemoryStream(); ms.Write(buffer, 0, buffer.Length); //ms.WriteString(content); return ms; } /// <summary> /// /// </summary> public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } /// <summary> /// /// </summary> public override bool CanWrite { get { return true; } } /// <summary> /// /// </summary> public override long Length { get { return 0; } } /// <summary> /// /// </summary> public override long Position { get { return _position; } set { _position = value; } } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="direction"></param> /// <returns></returns> public override long Seek(long offset, System.IO.SeekOrigin direction) { return _stream.Seek(offset, direction); } /// <summary> /// /// </summary> /// <param name="length"></param> public override void SetLength(long length) { _stream.SetLength(length); } /// <summary> /// /// </summary> public override void Close() { _stream.Close(); } /// <summary> /// Override flush by writing out the cached stream data /// </summary> public override void Flush() { if (IsCaptured && _cacheStream.Length > 0) { // Check for transform implementations _cacheStream = OnTransformCompleteStream(_cacheStream); _cacheStream = OnTransformCompleteStringInternal(_cacheStream); OnCaptureStream(_cacheStream); OnCaptureStringInternal(_cacheStream); // write the stream back out if output was delayed if (IsOutputDelayed) _stream.Write(_cacheStream.ToArray(), 0, (int)_cacheStream.Length); // Clear the cache once we've written it out _cacheStream.SetLength(0); } // default flush behavior _stream.Flush(); } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override int Read(byte[] buffer, int offset, int count) { return _stream.Read(buffer, offset, count); } /// <summary> /// Overriden to capture output written by ASP.NET and captured /// into a cached stream that is written out later when Flush() /// is called. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public override void Write(byte[] buffer, int offset, int count) { if ( IsCaptured ) { // copy to holding buffer only - we'll write out later _cacheStream.Write(buffer, 0, count); _cachePointer += count; } // just transform this buffer if (TransformWrite != null) buffer = OnTransformWrite(buffer); if (TransformWriteString != null) buffer = OnTransformWriteStringInternal(buffer); if (!IsOutputDelayed) _stream.Write(buffer, offset, buffer.Length); } } The key features are the events and corresponding OnXXX methods that handle the event hookups, and the Write() and Flush() methods of the stream implementation. All the rest of the members tend to be plain jane passthrough stream implementation code without much consequence. I do love the way Action<t> and Func<T> make it so easy to create the event signatures for the various events – sweet. A few Things to consider Performance Response.Filter is not great for performance in general as it adds another layer of indirection to the ASP.NET output pipeline, and this implementation in particular adds a memory hit as it basically duplicates the response output into the cached memory stream which is necessary since you may have to look at the entire response. If you have large pages in particular this can cause potentially serious memory pressure in your server application. So be careful of wholesale adoption of this (or other) Response.Filters. Make sure to do some performance testing to ensure it’s not killing your app’s performance. Response.Filter works everywhere A few questions came up in comments and discussion as to capturing ALL output hitting the site and – yes you can definitely do that by assigning a Response.Filter inside of a module. If you do this however you’ll want to be very careful and decide which content you actually want to capture especially in IIS 7 which passes ALL content – including static images/CSS etc. through the ASP.NET pipeline. So it is important to filter only on what you’re looking for – like the page extension or maybe more effectively the Response.ContentType. Response.Filter Chaining Originally I thought that filter chaining doesn’t work at all due to a bug in the stream implementation code. But it’s quite possible to assign multiple filters to the Response.Filter property. So the following actually works to both compress the output and apply the transformed content: WebUtils.GZipEncodePage(); ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformString += filter_TransformString; Response.Filter = filter; However the following does not work resulting in invalid content encoding errors: ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformString += filter_TransformString; Response.Filter = filter; WebUtils.GZipEncodePage(); In other words multiple Response filters can work together but it depends entirely on the implementation whether they can be chained or in which order they can be chained. In this case running the GZip/Deflate stream filters apparently relies on the original content length of the output and chokes when the content is modified. But if attaching the compression first it works fine as unintuitive as that may seem. Resources Download example code Capture Output from ASP.NET Pages © Rick Strahl, West Wind Technologies, 2005-2010Posted in ASP.NET  

    Read the article

  • custom collection in property grid

    - by guyl
    Hi guys. I'm using this article as a reference to use custom collection in propertygrid: LINK When I open the collectioneditor and remove all items then I press OK, I get an exception if null. How can i solve that ? I am using: public T this[int index] { get { if (List.Count == 0) { return default(T); } else { return (T)this.List[index]; } } } as a getter for an item, of course if I have no object how can i restart the whole collection ? this is the whole code /// <summary> /// A generic folder settings collection to use in a property grid. /// </summary> /// <typeparam name="T">can be import or export folder settings.</typeparam> [Serializable] [TypeConverter(typeof(FolderSettingsCollectionConverter)), Editor(typeof(FolderSettingsCollectionEditor), typeof(UITypeEditor))] public class FolderSettingsCollection_New<T> : CollectionBase, ICustomTypeDescriptor { private bool m_bRestrictNumberOfItems; private int m_bNumberOfItems; private Dictionary<string, int> m_UID2Idx = new Dictionary<string, int>(); private T[] arrTmp; /// <summary> /// C'tor, can determine the number of objects to hold. /// </summary> /// <param name="bRestrictNumberOfItems">restrict the number of folders to hold.</param> /// <param name="iNumberOfItems">The number of folders to hold.</param> public FolderSettingsCollection_New(bool bRestrictNumberOfItems = false , int iNumberOfItems = 1) { m_bRestrictNumberOfItems = bRestrictNumberOfItems; m_bNumberOfItems = iNumberOfItems; } /// <summary> /// Add folder to collection. /// </summary> /// <param name="t">Folder to add.</param> public void Add(T t) { if (m_bRestrictNumberOfItems) { if (this.List.Count >= m_bNumberOfItems) { return; } } int index = this.List.Add(t); if (t is WriteDataFolderSettings || t is ReadDataFolderSettings) { FolderSettingsBase tmp = t as FolderSettingsBase; m_UID2Idx.Add(tmp.UID, index); } } /// <summary> /// Remove folder to collection. /// </summary> /// <param name="t">Folder to remove.</param> public void Remove(T t) { this.List.Remove(t); if (t is WriteDataFolderSettings || t is ReadDataFolderSettings) { FolderSettingsBase tmp = t as FolderSettingsBase; m_UID2Idx.Remove(tmp.UID); } } /// <summary> /// Gets ot sets a folder. /// </summary> /// <param name="index">The index of the folder in the collection.</param> /// <returns>A folder object.</returns> public T this[int index] { get { //if (List.Count == 0) //{ // return default(T); //} //else //{ return (T)this.List[index]; //} } } /// <summary> /// Gets or sets a folder. /// </summary> /// <param name="sUID">The UID of the folder.</param> /// <returns>A folder object.</returns> public T this[string sUID] { get { if (this.Count == 0 || !m_UID2Idx.ContainsKey(sUID)) { return default(T); } else { return (T)this.List[m_UID2Idx[sUID]]; } } } /// <summary> /// /// </summary> /// <param name="sUID"></param> /// <returns></returns> public bool ContainsItemByUID(string sUID) { return m_UID2Idx.ContainsKey(sUID); } /// <summary> /// /// </summary> /// <returns></returns> public String GetClassName() { return TypeDescriptor.GetClassName(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public String GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } /// <summary> /// /// </summary> /// <param name="editorBaseType"></param> /// <returns></returns> public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// <summary> /// /// </summary> /// <param name="attributes"></param> /// <returns></returns> public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } /// <summary> /// /// </summary> /// <returns></returns> public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } /// <summary> /// /// </summary> /// <param name="pd"></param> /// <returns></returns> public object GetPropertyOwner(PropertyDescriptor pd) { return this; } /// <summary> /// /// </summary> /// <param name="attributes"></param> /// <returns></returns> public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return GetProperties(); } /// <summary> /// Called to get the properties of this type. /// </summary> /// <returns></returns> public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list of employees for (int i = 0; i < this.List.Count; i++) { // Create a property descriptor for the employee item and add to the property descriptor collection CollectionPropertyDescriptor_New<T> pd = new CollectionPropertyDescriptor_New<T>(this, i); pds.Add(pd); } // return the property descriptor collection return pds; } public T[] ToArray() { if (arrTmp == null) { arrTmp = new T[List.Count]; for (int i = 0; i < List.Count; i++) { arrTmp[i] = (T)List[i]; } } return arrTmp; } } /// <summary> /// Enable to display data about a collection in a property grid. /// </summary> /// <typeparam name="T">Folder object.</typeparam> public class CollectionPropertyDescriptor_New<T> : PropertyDescriptor { private FolderSettingsCollection_New<T> collection = null; private int index = -1; /// <summary> /// /// </summary> /// <param name="coll"></param> /// <param name="idx"></param> public CollectionPropertyDescriptor_New(FolderSettingsCollection_New<T> coll, int idx) : base("#" + idx.ToString(), null) { this.collection = coll; this.index = idx; } /// <summary> /// /// </summary> public override AttributeCollection Attributes { get { return new AttributeCollection(null); } } /// <summary> /// /// </summary> /// <param name="component"></param> /// <returns></returns> public override bool CanResetValue(object component) { return true; } /// <summary> /// /// </summary> public override Type ComponentType { get { return this.collection.GetType(); } } /// <summary> /// /// </summary> public override string DisplayName { get { if (this.collection[index] != null) { return this.collection[index].ToString(); } else { return null; } } } public override string Description { get { return ""; } } /// <summary> /// /// </summary> /// <param name="component"></param> /// <returns></returns> public override object GetValue(object component) { if (this.collection[index] != null) { return this.collection[index]; } else { return null; } } /// <summary> /// /// </summary> public override bool IsReadOnly { get { return false; } } public override string Name { get { return "#" + index.ToString(); } } /// <summary> /// /// </summary> public override Type PropertyType { get { return this.collection[index].GetType(); } } public override void ResetValue(object component) { } /// <summary> /// /// </summary> /// <param name="component"></param> /// <returns></returns> public override bool ShouldSerializeValue(object component) { return true; } /// <summary> /// /// </summary> /// <param name="component"></param> /// <param name="value"></param> public override void SetValue(object component, object value) { // this.collection[index] = value; } }

    Read the article

  • Introducing the Earthquake Locator – A Bing Maps Silverlight Application, part 1

    - by Bobby Diaz
    Update: Live demo and source code now available!  The recent wave of earthquakes (no pun intended) being reported in the news got me wondering about the frequency and severity of earthquakes around the world. Since I’ve been doing a lot of Silverlight development lately, I decided to scratch my curiosity with a nice little Bing Maps application that will show the location and relative strength of recent seismic activity. Here is a list of technologies this application will utilize, so be sure to have everything downloaded and installed if you plan on following along. Silverlight 3 WCF RIA Services Bing Maps Silverlight Control * Managed Extensibility Framework (optional) MVVM Light Toolkit (optional) log4net (optional) * If you are new to Bing Maps or have not signed up for a Developer Account, you will need to visit www.bingmapsportal.com to request a Bing Maps key for your application. Getting Started We start out by creating a new Silverlight Application called EarthquakeLocator and specify that we want to automatically create the Web Application Project with RIA Services enabled. I cleaned up the web app by removing the Default.aspx and EarthquakeLocatorTestPage.html. Then I renamed the EarthquakeLocatorTestPage.aspx to Default.aspx and set it as my start page. I also set the development server to use a specific port, as shown below. RIA Services Next, I created a Services folder in the EarthquakeLocator.Web project and added a new Domain Service Class called EarthquakeService.cs. This is the RIA Services Domain Service that will provide earthquake data for our client application. I am not using LINQ to SQL or Entity Framework, so I will use the <empty domain service class> option. We will be pulling data from an external Atom feed, but this example could just as easily pull data from a database or another web service. This is an important distinction to point out because each scenario I just mentioned could potentially use a different Domain Service base class (i.e. LinqToSqlDomainService<TDataContext>). Now we can start adding Query methods to our EarthquakeService that pull data from the USGS web site. Here is the complete code for our service class: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.ServiceModel.Syndication; using System.Web.DomainServices; using System.Web.Ria; using System.Xml; using log4net; using EarthquakeLocator.Web.Model;   namespace EarthquakeLocator.Web.Services {     /// <summary>     /// Provides earthquake data to client applications.     /// </summary>     [EnableClientAccess()]     public class EarthquakeService : DomainService     {         private static readonly ILog log = LogManager.GetLogger(typeof(EarthquakeService));           // USGS Data Feeds: http://earthquake.usgs.gov/earthquakes/catalogs/         private const string FeedForPreviousDay =             "http://earthquake.usgs.gov/earthquakes/catalogs/1day-M2.5.xml";         private const string FeedForPreviousWeek =             "http://earthquake.usgs.gov/earthquakes/catalogs/7day-M2.5.xml";           /// <summary>         /// Gets the earthquake data for the previous week.         /// </summary>         /// <returns>A queryable collection of <see cref="Earthquake"/> objects.</returns>         public IQueryable<Earthquake> GetEarthquakes()         {             var feed = GetFeed(FeedForPreviousWeek);             var list = new List<Earthquake>();               if ( feed != null )             {                 foreach ( var entry in feed.Items )                 {                     var quake = CreateEarthquake(entry);                     if ( quake != null )                     {                         list.Add(quake);                     }                 }             }               return list.AsQueryable();         }           /// <summary>         /// Creates an <see cref="Earthquake"/> object for each entry in the Atom feed.         /// </summary>         /// <param name="entry">The Atom entry.</param>         /// <returns></returns>         private Earthquake CreateEarthquake(SyndicationItem entry)         {             Earthquake quake = null;             string title = entry.Title.Text;             string summary = entry.Summary.Text;             string point = GetElementValue<String>(entry, "point");             string depth = GetElementValue<String>(entry, "elev");             string utcTime = null;             string localTime = null;             string depthDesc = null;             double? magnitude = null;             double? latitude = null;             double? longitude = null;             double? depthKm = null;               if ( !String.IsNullOrEmpty(title) && title.StartsWith("M") )             {                 title = title.Substring(2, title.IndexOf(',')-3).Trim();                 magnitude = TryParse(title);             }             if ( !String.IsNullOrEmpty(point) )             {                 var values = point.Split(' ');                 if ( values.Length == 2 )                 {                     latitude = TryParse(values[0]);                     longitude = TryParse(values[1]);                 }             }             if ( !String.IsNullOrEmpty(depth) )             {                 depthKm = TryParse(depth);                 if ( depthKm != null )                 {                     depthKm = Math.Round((-1 * depthKm.Value) / 100, 2);                 }             }             if ( !String.IsNullOrEmpty(summary) )             {                 summary = summary.Replace("</p>", "");                 var values = summary.Split(                     new string[] { "<p>" },                     StringSplitOptions.RemoveEmptyEntries);                   if ( values.Length == 3 )                 {                     var times = values[1].Split(                         new string[] { "<br>" },                         StringSplitOptions.RemoveEmptyEntries);                       if ( times.Length > 0 )                     {                         utcTime = times[0];                     }                     if ( times.Length > 1 )                     {                         localTime = times[1];                     }                       depthDesc = values[2];                     depthDesc = "Depth: " + depthDesc.Substring(depthDesc.IndexOf(":") + 2);                 }             }               if ( latitude != null && longitude != null )             {                 quake = new Earthquake()                 {                     Id = entry.Id,                     Title = entry.Title.Text,                     Summary = entry.Summary.Text,                     Date = entry.LastUpdatedTime.DateTime,                     Url = entry.Links.Select(l => Path.Combine(l.BaseUri.OriginalString,                         l.Uri.OriginalString)).FirstOrDefault(),                     Age = entry.Categories.Where(c => c.Label == "Age")                         .Select(c => c.Name).FirstOrDefault(),                     Magnitude = magnitude.GetValueOrDefault(),                     Latitude = latitude.GetValueOrDefault(),                     Longitude = longitude.GetValueOrDefault(),                     DepthInKm = depthKm.GetValueOrDefault(),                     DepthDesc = depthDesc,                     UtcTime = utcTime,                     LocalTime = localTime                 };             }               return quake;         }           private T GetElementValue<T>(SyndicationItem entry, String name)         {             var el = entry.ElementExtensions.Where(e => e.OuterName == name).FirstOrDefault();             T value = default(T);               if ( el != null )             {                 value = el.GetObject<T>();             }               return value;         }           private double? TryParse(String value)         {             double d;             if ( Double.TryParse(value, out d) )             {                 return d;             }             return null;         }           /// <summary>         /// Gets the feed at the specified URL.         /// </summary>         /// <param name="url">The URL.</param>         /// <returns>A <see cref="SyndicationFeed"/> object.</returns>         public static SyndicationFeed GetFeed(String url)         {             SyndicationFeed feed = null;               try             {                 log.Debug("Loading RSS feed: " + url);                   using ( var reader = XmlReader.Create(url) )                 {                     feed = SyndicationFeed.Load(reader);                 }             }             catch ( Exception ex )             {                 log.Error("Error occurred while loading RSS feed: " + url, ex);             }               return feed;         }     } }   The only method that will be generated in the client side proxy class, EarthquakeContext, will be the GetEarthquakes() method. The reason being that it is the only public instance method and it returns an IQueryable<Earthquake> collection that can be consumed by the client application. GetEarthquakes() calls the static GetFeed(String) method, which utilizes the built in SyndicationFeed API to load the external data feed. You will need to add a reference to the System.ServiceModel.Web library in order to take advantage of the RSS/Atom reader. The API will also allow you to create your own feeds to serve up in your applications. Model I have also created a Model folder and added a new class, Earthquake.cs. The Earthquake object will hold the various properties returned from the Atom feed. Here is a sample of the code for that class. Notice the [Key] attribute on the Id property, which is required by RIA Services to uniquely identify the entity. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ComponentModel.DataAnnotations;   namespace EarthquakeLocator.Web.Model {     /// <summary>     /// Represents an earthquake occurrence and related information.     /// </summary>     [DataContract]     public class Earthquake     {         /// <summary>         /// Gets or sets the id.         /// </summary>         /// <value>The id.</value>         [Key]         [DataMember]         public string Id { get; set; }           /// <summary>         /// Gets or sets the title.         /// </summary>         /// <value>The title.</value>         [DataMember]         public string Title { get; set; }           /// <summary>         /// Gets or sets the summary.         /// </summary>         /// <value>The summary.</value>         [DataMember]         public string Summary { get; set; }           // additional properties omitted     } }   View Model The recent trend to use the MVVM pattern for WPF and Silverlight provides a great way to separate the data and behavior logic out of the user interface layer of your client applications. I have chosen to use the MVVM Light Toolkit for the Earthquake Locator, but there are other options out there if you prefer another library. That said, I went ahead and created a ViewModel folder in the Silverlight project and added a EarthquakeViewModel class that derives from ViewModelBase. Here is the code: using System; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using Microsoft.Maps.MapControl; using GalaSoft.MvvmLight; using EarthquakeLocator.Web.Model; using EarthquakeLocator.Web.Services;   namespace EarthquakeLocator.ViewModel {     /// <summary>     /// Provides data for views displaying earthquake information.     /// </summary>     public class EarthquakeViewModel : ViewModelBase     {         [Import]         public EarthquakeContext Context;           /// <summary>         /// Initializes a new instance of the <see cref="EarthquakeViewModel"/> class.         /// </summary>         public EarthquakeViewModel()         {             var catalog = new AssemblyCatalog(GetType().Assembly);             var container = new CompositionContainer(catalog);             container.ComposeParts(this);             Initialize();         }           /// <summary>         /// Initializes a new instance of the <see cref="EarthquakeViewModel"/> class.         /// </summary>         /// <param name="context">The context.</param>         public EarthquakeViewModel(EarthquakeContext context)         {             Context = context;             Initialize();         }           private void Initialize()         {             MapCenter = new Location(20, -170);             ZoomLevel = 2;         }           #region Private Methods           private void OnAutoLoadDataChanged()         {             LoadEarthquakes();         }           private void LoadEarthquakes()         {             var query = Context.GetEarthquakesQuery();             Context.Earthquakes.Clear();               Context.Load(query, (op) =>             {                 if ( !op.HasError )                 {                     foreach ( var item in op.Entities )                     {                         Earthquakes.Add(item);                     }                 }             }, null);         }           #endregion Private Methods           #region Properties           private bool autoLoadData;         /// <summary>         /// Gets or sets a value indicating whether to auto load data.         /// </summary>         /// <value><c>true</c> if auto loading data; otherwise, <c>false</c>.</value>         public bool AutoLoadData         {             get { return autoLoadData; }             set             {                 if ( autoLoadData != value )                 {                     autoLoadData = value;                     RaisePropertyChanged("AutoLoadData");                     OnAutoLoadDataChanged();                 }             }         }           private ObservableCollection<Earthquake> earthquakes;         /// <summary>         /// Gets the collection of earthquakes to display.         /// </summary>         /// <value>The collection of earthquakes.</value>         public ObservableCollection<Earthquake> Earthquakes         {             get             {                 if ( earthquakes == null )                 {                     earthquakes = new ObservableCollection<Earthquake>();                 }                   return earthquakes;             }         }           private Location mapCenter;         /// <summary>         /// Gets or sets the map center.         /// </summary>         /// <value>The map center.</value>         public Location MapCenter         {             get { return mapCenter; }             set             {                 if ( mapCenter != value )                 {                     mapCenter = value;                     RaisePropertyChanged("MapCenter");                 }             }         }           private double zoomLevel;         /// <summary>         /// Gets or sets the zoom level.         /// </summary>         /// <value>The zoom level.</value>         public double ZoomLevel         {             get { return zoomLevel; }             set             {                 if ( zoomLevel != value )                 {                     zoomLevel = value;                     RaisePropertyChanged("ZoomLevel");                 }             }         }           #endregion Properties     } }   The EarthquakeViewModel class contains all of the properties that will be bound to by the various controls in our views. Be sure to read through the LoadEarthquakes() method, which handles calling the GetEarthquakes() method in our EarthquakeService via the EarthquakeContext proxy, and also transfers the loaded entities into the view model’s Earthquakes collection. Another thing to notice is what’s going on in the default constructor. I chose to use the Managed Extensibility Framework (MEF) for my composition needs, but you can use any dependency injection library or none at all. To allow the EarthquakeContext class to be discoverable by MEF, I added the following partial class so that I could supply the appropriate [Export] attribute: using System; using System.ComponentModel.Composition;   namespace EarthquakeLocator.Web.Services {     /// <summary>     /// The client side proxy for the EarthquakeService class.     /// </summary>     [Export]     public partial class EarthquakeContext     {     } }   One last piece I wanted to point out before moving on to the user interface, I added a client side partial class for the Earthquake entity that contains helper properties that we will bind to later: using System;   namespace EarthquakeLocator.Web.Model {     /// <summary>     /// Represents an earthquake occurrence and related information.     /// </summary>     public partial class Earthquake     {         /// <summary>         /// Gets the location based on the current Latitude/Longitude.         /// </summary>         /// <value>The location.</value>         public string Location         {             get { return String.Format("{0},{1}", Latitude, Longitude); }         }           /// <summary>         /// Gets the size based on the Magnitude.         /// </summary>         /// <value>The size.</value>         public double Size         {             get { return (Magnitude * 3); }         }     } }   View Now the fun part! Usually, I would create a Views folder to place all of my View controls in, but I took the easy way out and added the following XAML code to the default MainPage.xaml file. Be sure to add the bing prefix associating the Microsoft.Maps.MapControl namespace after adding the assembly reference to your project. The MVVM Light Toolkit project templates come with a ViewModelLocator class that you can use via a static resource, but I am instantiating the EarthquakeViewModel directly in my user control. I am setting the AutoLoadData property to true as a way to trigger the LoadEarthquakes() method call. The MapItemsControl found within the <bing:Map> control binds its ItemsSource property to the Earthquakes collection of the view model, and since it is an ObservableCollection<T>, we get the automatic two way data binding via the INotifyCollectionChanged interface. <UserControl x:Class="EarthquakeLocator.MainPage"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     xmlns:bing="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"     xmlns:vm="clr-namespace:EarthquakeLocator.ViewModel"     mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480" >     <UserControl.Resources>         <DataTemplate x:Key="EarthquakeTemplate">             <Ellipse Fill="Red" Stroke="Black" StrokeThickness="1"                      Width="{Binding Size}" Height="{Binding Size}"                      bing:MapLayer.Position="{Binding Location}"                      bing:MapLayer.PositionOrigin="Center">                 <ToolTipService.ToolTip>                     <StackPanel>                         <TextBlock Text="{Binding Title}" FontSize="14" FontWeight="Bold" />                         <TextBlock Text="{Binding UtcTime}" />                         <TextBlock Text="{Binding LocalTime}" />                         <TextBlock Text="{Binding DepthDesc}" />                     </StackPanel>                 </ToolTipService.ToolTip>             </Ellipse>         </DataTemplate>     </UserControl.Resources>       <UserControl.DataContext>         <vm:EarthquakeViewModel AutoLoadData="True" />     </UserControl.DataContext>       <Grid x:Name="LayoutRoot">           <bing:Map x:Name="map" CredentialsProvider="--Your-Bing-Maps-Key--"                   Center="{Binding MapCenter, Mode=TwoWay}"                   ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}">             <bing:MapItemsControl ItemsSource="{Binding Earthquakes}"                                   ItemTemplate="{StaticResource EarthquakeTemplate}" />         </bing:Map>       </Grid> </UserControl>   The EarthquakeTemplate defines the Ellipse that will represent each earthquake, the Width and Height that are determined by the Magnitude, the Position on the map, and also the tooltip that will appear when we mouse over each data point. Running the application will give us the following result (shown with a tooltip example): That concludes this portion of our show but I plan on implementing additional functionality in later blog posts. Be sure to come back soon to see the next installments in this series. Enjoy!   Additional Resources USGS Earthquake Data Feeds Brad Abrams shows how RIA Services and MVVM can work together

    Read the article

  • Why do I get an exception when playing multiple sound instances?

    - by Boreal
    Right now, I'm adding a rudimentary sound engine to my game. So far, I am able to load in a WAV file and play it once, then free up the memory when I close the game. However, the game crashes with a nice ArgumentOutOfBoundsException when I try to play another sound instance. Specified argument was out of the range of valid values. Parameter name: readLength I'm following this tutorial pretty much exactly, but I still keep getting the aforementioned error. Here's my sound-related code. /// <summary> /// Manages all sound instances. /// </summary> public static class Audio { static XAudio2 device; static MasteringVoice master; static List<SoundInstance> instances; /// <summary> /// The XAudio2 device. /// </summary> internal static XAudio2 Device { get { return device; } } /// <summary> /// Initializes the audio device and master track. /// </summary> internal static void Initialize() { device = new XAudio2(); master = new MasteringVoice(device); instances = new List<SoundInstance>(); } /// <summary> /// Releases all XA2 resources. /// </summary> internal static void Shutdown() { foreach(SoundInstance i in instances) i.Dispose(); master.Dispose(); device.Dispose(); } /// <summary> /// Registers a sound instance with the system. /// </summary> /// <param name="instance">Sound instance</param> internal static void AddInstance(SoundInstance instance) { instances.Add(instance); } /// <summary> /// Disposes any sound instance that has stopped playing. /// </summary> internal static void Update() { List<SoundInstance> temp = new List<SoundInstance>(instances); foreach(SoundInstance i in temp) if(!i.Playing) { i.Dispose(); instances.Remove(i); } } } /// <summary> /// Loads sounds from various files. /// </summary> internal class SoundLoader { /// <summary> /// Loads a .wav sound file. /// </summary> /// <param name="format">The decoded format will be sent here</param> /// <param name="buffer">The data will be sent here</param> /// <param name="soundName">The path to the WAV file</param> internal static void LoadWAV(out WaveFormat format, out AudioBuffer buffer, string soundName) { WaveStream wave = new WaveStream(soundName); format = wave.Format; buffer = new AudioBuffer(); buffer.AudioData = wave; buffer.AudioBytes = (int)wave.Length; buffer.Flags = BufferFlags.EndOfStream; } } /// <summary> /// Manages the data for a single sound. /// </summary> public class Sound : IAsset { WaveFormat format; AudioBuffer buffer; /// <summary> /// Loads a sound from a file. /// </summary> /// <param name="soundName">The path to the sound file</param> /// <returns>Whether the sound loaded successfully</returns> public bool Load(string soundName) { if(soundName.EndsWith(".wav")) SoundLoader.LoadWAV(out format, out buffer, soundName); else return false; return true; } /// <summary> /// Plays the sound. /// </summary> public void Play() { Audio.AddInstance(new SoundInstance(format, buffer)); } /// <summary> /// Unloads the sound from memory. /// </summary> public void Unload() { buffer.Dispose(); } } /// <summary> /// Manages a single sound instance. /// </summary> public class SoundInstance { SourceVoice source; bool playing; /// <summary> /// Whether the sound is currently playing. /// </summary> public bool Playing { get { return playing; } } /// <summary> /// Starts a new instance of a sound. /// </summary> /// <param name="format">Format of the sound</param> /// <param name="buffer">Buffer holding sound data</param> internal SoundInstance(WaveFormat format, AudioBuffer buffer) { source = new SourceVoice(Audio.Device, format); source.BufferEnd += (s, e) => playing = false; source.Start(); source.SubmitSourceBuffer(buffer); // THIS IS WHERE THE EXCEPTION IS THROWN playing = true; } /// <summary> /// Releases memory used by the instance. /// </summary> internal void Dispose() { source.Dispose(); } } The exception occurs on line 156 when I am playing the sound: source.SubmitSourceBuffer(buffer);

    Read the article

  • Setting Up and Running Summary Advisor on an Exalytics Machine (Oracle-by-Example)

    - by Saresh
    If you are running Oracle BI on an Exalytics machine, you can use Summary Advisor to identify the aggregates that will increase query performance. Summary Advisor intelligently recommends an optimal list of aggregate tables based on query patterns that will achieve maximum query performance gain while meeting specific resource constraints. Summary Advisor then generates an aggregate creation script that can be run to create the recommended aggregate tables. Aggregate tables reduce query times by storing precomputed results for queries that include rolled-up data. This tutorial covers steps to set up, configure, and run Summary Advisor on an Exalytics machine using TimesTen database as a target for storing aggregates. You can find the Oracle By Example (OBE) in the Oracle Learning Library (OLL). The content in OLL is available to all customers, partners, and employees.

    Read the article

  • Asp.net Custom user control button. How to stop multiple clicks by user.

    - by Laurence Burke
    I am trying to modify an open source Forum called YetAnotherForum.net in the project they have a custom user control called Yaf:ThemeButton. Now its rendered as an anchor with an onclick method in this code ThemeButton.cs using System; using System.Web.UI; using System.Web.UI.WebControls; namespace YAF.Controls { /// <summary> /// The theme button. /// </summary> public class ThemeButton : BaseControl, IPostBackEventHandler { /// <summary> /// The _click event. /// </summary> protected static object _clickEvent = new object(); /// <summary> /// The _command event. /// </summary> protected static object _commandEvent = new object(); /// <summary> /// The _attribute collection. /// </summary> protected AttributeCollection _attributeCollection; /// <summary> /// The _localized label. /// </summary> protected LocalizedLabel _localizedLabel = new LocalizedLabel(); /// <summary> /// The _theme image. /// </summary> protected ThemeImage _themeImage = new ThemeImage(); /// <summary> /// Initializes a new instance of the <see cref="ThemeButton"/> class. /// </summary> public ThemeButton() : base() { Load += new EventHandler(ThemeButton_Load); this._attributeCollection = new AttributeCollection(ViewState); } /// <summary> /// ThemePage for the optional button image /// </summary> public string ImageThemePage { get { return this._themeImage.ThemePage; } set { this._themeImage.ThemePage = value; } } /// <summary> /// ThemeTag for the optional button image /// </summary> public string ImageThemeTag { get { return this._themeImage.ThemeTag; } set { this._themeImage.ThemeTag = value; } } /// <summary> /// Localized Page for the optional button text /// </summary> public string TextLocalizedPage { get { return this._localizedLabel.LocalizedPage; } set { this._localizedLabel.LocalizedPage = value; } } /// <summary> /// Localized Tag for the optional button text /// </summary> public string TextLocalizedTag { get { return this._localizedLabel.LocalizedTag; } set { this._localizedLabel.LocalizedTag = value; } } /// <summary> /// Defaults to "yafcssbutton" /// </summary> public string CssClass { get { return (ViewState["CssClass"] != null) ? ViewState["CssClass"] as string : "yafcssbutton"; } set { ViewState["CssClass"] = value; } } /// <summary> /// Setting the link property will make this control non-postback. /// </summary> public string NavigateUrl { get { return (ViewState["NavigateUrl"] != null) ? ViewState["NavigateUrl"] as string : string.Empty; } set { ViewState["NavigateUrl"] = value; } } /// <summary> /// Localized Page for the optional link description (title) /// </summary> public string TitleLocalizedPage { get { return (ViewState["TitleLocalizedPage"] != null) ? ViewState["TitleLocalizedPage"] as string : "BUTTON"; } set { ViewState["TitleLocalizedPage"] = value; } } /// <summary> /// Localized Tag for the optional link description (title) /// </summary> public string TitleLocalizedTag { get { return (ViewState["TitleLocalizedTag"] != null) ? ViewState["TitleLocalizedTag"] as string : string.Empty; } set { ViewState["TitleLocalizedTag"] = value; } } /// <summary> /// Non-localized Title for optional link description /// </summary> public string TitleNonLocalized { get { return (ViewState["TitleNonLocalized"] != null) ? ViewState["TitleNonLocalized"] as string : string.Empty; } set { ViewState["TitleNonLocalized"] = value; } } /// <summary> /// Gets Attributes. /// </summary> public AttributeCollection Attributes { get { return this._attributeCollection; } } /// <summary> /// Gets or sets CommandName. /// </summary> public string CommandName { get { if (ViewState["commandName"] != null) { return ViewState["commandName"].ToString(); } return null; } set { ViewState["commandName"] = value; } } /// <summary> /// Gets or sets CommandArgument. /// </summary> public string CommandArgument { get { if (ViewState["commandArgument"] != null) { return ViewState["commandArgument"].ToString(); } return null; } set { ViewState["commandArgument"] = value; } } #region IPostBackEventHandler Members /// <summary> /// The i post back event handler. raise post back event. /// </summary> /// <param name="eventArgument"> /// The event argument. /// </param> void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { OnCommand(new CommandEventArgs(CommandName, CommandArgument)); OnClick(EventArgs.Empty); } #endregion /// <summary> /// Setup the controls before render /// </summary> /// <param name="sender"> /// </param> /// <param name="e"> /// </param> private void ThemeButton_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(this._themeImage.ThemeTag)) { // add the theme image... Controls.Add(this._themeImage); } // render the text if available if (!String.IsNullOrEmpty(this._localizedLabel.LocalizedTag)) { Controls.Add(this._localizedLabel); } } /// <summary> /// The render. /// </summary> /// <param name="output"> /// The output. /// </param> protected override void Render(HtmlTextWriter output) { // get the title... string title = GetLocalizedTitle(); output.BeginRender(); output.WriteBeginTag("a"); output.WriteAttribute("id", ClientID); if (!String.IsNullOrEmpty(CssClass)) { output.WriteAttribute("class", CssClass); } if (!String.IsNullOrEmpty(title)) { output.WriteAttribute("title", title); } else if (!String.IsNullOrEmpty(TitleNonLocalized)) { output.WriteAttribute("title", TitleNonLocalized); } if (!String.IsNullOrEmpty(NavigateUrl)) { output.WriteAttribute("href", NavigateUrl.Replace("&", "&amp;")); } else { // string.Format("javascript:__doPostBack('{0}','{1}')",this.ClientID,"")); output.WriteAttribute("href", Page.ClientScript.GetPostBackClientHyperlink(this, string.Empty)); } bool wroteOnClick = false; // handle additional attributes (if any) if (this._attributeCollection.Count > 0) { // add attributes... foreach (string key in this._attributeCollection.Keys) { // get the attribute and write it... if (key.ToLower() == "onclick") { // special handling... add to it... output.WriteAttribute(key, string.Format("{0};{1}", this._attributeCollection[key], "this.blur();this.display='none';")); wroteOnClick = true; } else if (key.ToLower().StartsWith("on") || key.ToLower() == "rel" || key.ToLower() == "target") { // only write javascript attributes -- and a few other attributes... output.WriteAttribute(key, this._attributeCollection[key]); } } } // IE fix if (!wroteOnClick) { output.WriteAttribute("onclick", "this.blur();this.style.display='none';"); } output.Write(HtmlTextWriter.TagRightChar); output.WriteBeginTag("span"); output.Write(HtmlTextWriter.TagRightChar); // render the optional controls (if any) base.Render(output); output.WriteEndTag("span"); output.WriteEndTag("a"); output.EndRender(); } /// <summary> /// The get localized title. /// </summary> /// <returns> /// The get localized title. /// </returns> protected string GetLocalizedTitle() { if (Site != null && Site.DesignMode == true && !String.IsNullOrEmpty(TitleLocalizedTag)) { return String.Format("[TITLE:{0}]", TitleLocalizedTag); } else if (!String.IsNullOrEmpty(TitleLocalizedPage) && !String.IsNullOrEmpty(TitleLocalizedTag)) { return PageContext.Localization.GetText(TitleLocalizedPage, TitleLocalizedTag); } else if (!String.IsNullOrEmpty(TitleLocalizedTag)) { return PageContext.Localization.GetText(TitleLocalizedTag); } return null; } /// <summary> /// The on click. /// </summary> /// <param name="e"> /// The e. /// </param> protected virtual void OnClick(EventArgs e) { var handler = (EventHandler) Events[_clickEvent]; if (handler != null) { handler(this, e); } } /// <summary> /// The on command. /// </summary> /// <param name="e"> /// The e. /// </param> protected virtual void OnCommand(CommandEventArgs e) { var handler = (CommandEventHandler) Events[_commandEvent]; if (handler != null) { handler(this, e); } RaiseBubbleEvent(this, e); } /// <summary> /// The click. /// </summary> public event EventHandler Click { add { Events.AddHandler(_clickEvent, value); } remove { Events.RemoveHandler(_clickEvent, value); } } /// <summary> /// The command. /// </summary> public event CommandEventHandler Command { add { Events.AddHandler(_commandEvent, value); } remove { Events.RemoveHandler(_commandEvent, value); } } } } now that is just cs file its handled like this in the .ascx page of the actual website <YAF:ThemeButton ID="Save" runat="server" CssClass="yafcssbigbutton leftItem" TextLocalizedTag="SAVE" OnClick="Save_Click" /> now it is given an OnClick codebehind function that does some serverside function like this protected void Save_Click(object sender, EventArgs e) { //some serverside code here } now I have a problem with the user being able to click multiple times and firing that serverside function multiple times. I have added in the code as of right now an extra onclick="this.style.display='none'" in the .cs code but that is a ugly fix I was wondering if anyone would have a better idea of disabling the ThemeButton clientside?? pls any feedback if I need to give more examples or further explain the question thanks.

    Read the article

  • Notification CeSetUserNotificationEx with custom sound

    - by inTagger
    Hail all! I want to display notification and play custom sound on my Windows Mobile 5/6 device. I have tried something like that, but my custom sound does not play, though message is displayed with standart sound. If i edit Wave key in [HKEY_CURRENT_USER\ControlPanel\Notifications{15F11F90-8A5F-454c-89FC-BA9B7AAB0CAD}] to sound file i need then it plays okay. But why there are flag NotificationAction.Sound and property UserNotification.Sound? It doesn't work. Also Vibration and Led don't work, if i use such flags. (You can obtain full project sources from http://dl.dropbox.com/u/1758206/Code/Thunder.zip) var trigger = new UserNotificationTrigger { StartTime = DateTime.Now + TimeSpan.FromSeconds(1), Type = NotificationType.ClassicTime }; var userNotification = new UserNotification { Sound = @"\Windows\Alarm1.wma", Text = "Hail from Penza, Russia!", Action = NotificationAction.Dialog | NotificationAction.Sound, Title = string.Empty, MaxSound = 16384 }; NotificationTools.SetUserNotification(0, trigger, userNotification); UserNotificationTrigger.cs: using System; using System.Runtime.InteropServices; namespace Thunder.Lib.ThunderMethod1 { /// <summary> /// Specifies the type of notification. /// </summary> public enum NotificationType { /// <summary> /// Equivalent to using the SetUserNotification function. /// The standard command line is supplied. /// </summary> ClassicTime = 4, /// <summary> /// System event notification. /// </summary> Event = 1, /// <summary> /// Time-based notification that is active for the time period between StartTime and EndTime. /// </summary> Period = 3, /// <summary> /// Time-based notification. /// </summary> Time = 2 } /// <summary> /// System Event Flags /// </summary> public enum NotificationEvent { None, TimeChange, SyncEnd, OnACPower, OffACPower, NetConnect, NetDisconnect, DeviceChange, IRDiscovered, RS232Detected, RestoreEnd, Wakeup, TimeZoneChange, MachineNameChange, RndisFNDetected, InternetProxyChange } /// <summary> /// Defines what event activates a notification. /// </summary> [StructLayout(LayoutKind.Sequential)] public class UserNotificationTrigger { internal int dwSize = 52; private int dwType; private int dwEvent; [MarshalAs(UnmanagedType.LPWStr)] private string lpszApplication = string.Empty; [MarshalAs(UnmanagedType.LPWStr)] private string lpszArguments; internal SYSTEMTIME stStartTime; internal SYSTEMTIME stEndTime; /// <summary> /// Specifies the type of notification. /// </summary> public NotificationType Type { get { return (NotificationType) dwType; } set { dwType = (int) value; } } /// <summary> /// Specifies the type of event should Type = Event. /// </summary> public NotificationEvent Event { get { return (NotificationEvent) dwEvent; } set { dwEvent = (int) value; } } /// <summary> /// Name of the application to execute. /// </summary> public string Application { get { return lpszApplication; } set { lpszApplication = value; } } /// <summary> /// Command line (without the application name). /// </summary> public string Arguments { get { return lpszArguments; } set { lpszArguments = value; } } /// <summary> /// Specifies the beginning of the notification period. /// </summary> public DateTime StartTime { get { return stStartTime.ToDateTime(); } set { stStartTime = SYSTEMTIME.FromDateTime(value); } } /// <summary> /// Specifies the end of the notification period. /// </summary> public DateTime EndTime { get { return stEndTime.ToDateTime(); } set { stEndTime = SYSTEMTIME.FromDateTime(value); } } } } UserNotification.cs: using System.Runtime.InteropServices; namespace Thunder.Lib.ThunderMethod1 { /// <summary> /// Contains information used for a user notification. /// </summary> [StructLayout(LayoutKind.Sequential)] public class UserNotification { private int ActionFlags; [MarshalAs(UnmanagedType.LPWStr)] private string pwszDialogTitle; [MarshalAs(UnmanagedType.LPWStr)] private string pwszDialogText; [MarshalAs(UnmanagedType.LPWStr)] private string pwszSound; private int nMaxSound; private int dwReserved; /// <summary> /// Any combination of the <see cref="T:Thunder.Lib.NotificationAction" /> members. /// </summary> /// <value>Flags which specifies the action(s) to be taken when the notification is triggered.</value> /// <remarks>Flags not valid on a given hardware platform will be ignored.</remarks> public NotificationAction Action { get { return (NotificationAction) ActionFlags; } set { ActionFlags = (int) value; } } /// <summary> /// Required if NotificationAction.Dialog is set, ignored otherwise /// </summary> public string Title { get { return pwszDialogTitle; } set { pwszDialogTitle = value; } } /// <summary> /// Required if NotificationAction.Dialog is set, ignored otherwise. /// </summary> public string Text { get { return pwszDialogText; } set { pwszDialogText = value; } } /// <summary> /// Sound string as supplied to PlaySound. /// </summary> public string Sound { get { return pwszSound; } set { pwszSound = value; } } public int MaxSound { get { return nMaxSound; } set { nMaxSound = value; } } } } NativeMethods.cs: using System; using System.Runtime.InteropServices; namespace Thunder.Lib.ThunderMethod1 { [StructLayout(LayoutKind.Sequential)] public struct SYSTEMTIME { public short wYear; public short wMonth; public short wDayOfWeek; public short wDay; public short wHour; public short wMinute; public short wSecond; public short wMillisecond; public static SYSTEMTIME FromDateTime(DateTime dt) { return new SYSTEMTIME { wYear = (short) dt.Year, wMonth = (short) dt.Month, wDayOfWeek = (short) dt.DayOfWeek, wDay = (short) dt.Day, wHour = (short) dt.Hour, wMinute = (short) dt.Minute, wSecond = (short) dt.Second, wMillisecond = (short) dt.Millisecond }; } public DateTime ToDateTime() { if ((((wYear == 0) && (wMonth == 0)) && ((wDay == 0) && (wHour == 0))) && ((wMinute == 0) && (wSecond == 0))) return DateTime.MinValue; return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMillisecond); } } /// <summary> /// Specifies the action to take when a notification event occurs. /// </summary> [Flags] public enum NotificationAction { /// <summary> /// Displays the user notification dialog box. /// </summary> Dialog = 4, /// <summary> /// Flashes the LED. /// </summary> Led = 1, /// <summary> /// Dialog box z-order flag. /// Set if the notification dialog box should come up behind the password. /// </summary> Private = 32, /// <summary> /// Repeats the sound for 10–15 seconds. /// </summary> Repeat = 16, /// <summary> /// Plays the sound specified. /// </summary> Sound = 8, /// <summary> /// Vibrates the device. /// </summary> Vibrate = 2 } internal class NativeMethods { [DllImport("coredll.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int CeSetUserNotificationEx(int hNotification, UserNotificationTrigger lpTrigger, UserNotification lpUserNotification); } } NotificationTools.cs: using System.ComponentModel; using System.Runtime.InteropServices; namespace Thunder.Lib.ThunderMethod1 { public static class NotificationTools { /// <summary> /// This function modifies an existing user notification. /// </summary> /// <param name="handle">Handle of the Notification to be modified</param> /// <param name="trigger">A UserNotificationTrigger that defines what event activates a notification.</param> /// <param name="notification">A UserNotification that defines how the system should respond when a notification occurs.</param> /// <returns>Handle to the notification event if successful.</returns> public static int SetUserNotification(int handle, UserNotificationTrigger trigger, UserNotification notification) { int num = NativeMethods.CeSetUserNotificationEx(handle, trigger, notification); if (num == 0) throw new Win32Exception(Marshal.GetLastWin32Error(), "Error setting UserNotification"); return num; } } }

    Read the article

  • ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)

    - by Soe Tun
    When we were working with ASP.NET MVC 2, we needed to write our own JavaScript to get Client-Side Validation Summary with jQuery Validation plugin. I am one of those unfortunate people still stuck with .NET Framework Runtime 2.0 and .NET Framework 3.5; meaning I am still on ASP.NET MVC 2. So I will still keep on supporting by answering any question you may have with my original code.   Long awaited ASP.NET MVC 3 has been released, and it supports Client Side Validation Summary with jQuery out-of-the-box with new features like Unobtrusive JavaScript.   1. _Layout.cshtml Template Notice that I am using Protocol Relative URLs ( i.e., '//'.  Not 'http://' or 'https://' ) to reference script files and css files and you should use it too like that! However, please note that IE7 and IE8 will download the CSS files twice so use it with judgement. <!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Assets/Site.css")" rel="stylesheet" type="text/css" /> <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" media="screen" /> </head> <body> @RenderBody() <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js" type="text/javascript"></script> <script src="//ajax.microsoft.com/ajax/jQuery.Validate/1.7/jQuery.Validate.min.js" type="text/javascript"></script> <script src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script> </body> </html>   2. MVC View Template There are 3 things you *must* do exactly to get Client Side Validation Summary working. (1)  You must declare your Validation Summary **inside** the `Html.BeginForm()` block like below. (2)  You must pass `excludePropertyErrors: false` to the  Html.ValidationSummary()  method. @using (Html.BeginForm()) { @Html.ValidationSummary(false, "Please fix these errors."); <!-- The rest of your View Template --> }   (3)  You have to put the following two elements in the `<appSettings />` block of your Web.config file. <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/>   That is all you need to do.  Simple, right? I will upload a sample project for download soon.  Please let me know if you run into some issues.     P.S: Without getting into too much technical details, I just wanted to let you know what I went through to get this to work. I had to look into the ASP.NET MVC 3 RTM Source Code and the jquery.validate.unobtrusive.js source. Initially, I thought I have to hack the jquery.validate.unobtrusive.js or something to get this to work. But after digging into MVC3 RTM source, I found out how to do it.

    Read the article

  • Maintaining State in Mud Engine

    - by Johnathon Sullinger
    I am currently working on a Mud Engine and have started implementing my state engine. One of the things that has me troubled is maintaining different states at once. For instance, lets say that the user has started a tutorial, which requires specific input. If the user types "help" I want to switch in to a help state, so they can get the help they need, then return them to the original state once exiting the help. my state system uses a State Manager to manage the state per user: public class StateManager { /// <summary> /// Gets the current state. /// </summary> public IState CurrentState { get; private set; } /// <summary> /// Gets the states available for use. /// </summary> /// <value> public List<IState> States { get; private set; } /// <summary> /// Gets the commands available. /// </summary> public List<ICommand> Commands { get; private set; } /// <summary> /// Gets the mob that this manager controls the state of. /// </summary> public IMob Mob { get; private set; } public void Initialize(IMob mob, IState initialState = null) { this.Mob = mob; if (initialState != null) { this.SwitchState(initialState); } } /// <summary> /// Performs the command. /// </summary> /// <param name="message">The message.</param> public void PerformCommand(IMessage message) { if (this.CurrentState != null) { ICommand command = this.CurrentState.GetCommand(message); if (command is NoOpCommand) { // NoOperation commands indicate that the current state is not finished yet. this.CurrentState.Render(this.Mob); } else if (command != null) { command.Execute(this.Mob); } else if (command == null) { new InvalidCommand().Execute(this.Mob); } } } /// <summary> /// Switches the state. /// </summary> /// <param name="state">The state.</param> public void SwitchState(IState state) { if (this.CurrentState != null) { this.CurrentState.Cleanup(); } this.CurrentState = state; if (state != null) { this.CurrentState.Render(this.Mob); } } } Each of the different states that the user can be in, is a Type implementing IState. public interface IState { /// <summary> /// Renders the current state to the players terminal. /// </summary> /// <param name="player">The player to render to</param> void Render(IMob mob); /// <summary> /// Gets the Command that the player entered and preps it for execution. /// </summary> /// <returns></returns> ICommand GetCommand(IMessage command); /// <summary> /// Cleanups this instance during a state change. /// </summary> void Cleanup(); } Example state: public class ConnectState : IState { /// <summary> /// The connected player /// </summary> private IMob connectedPlayer; public void Render(IMob mob) { if (!(mob is IPlayer)) { throw new NullReferenceException("ConnectState can only be used with a player object implementing IPlayer"); } //Store a reference for the GetCommand() method to use. this.connectedPlayer = mob as IPlayer; var server = mob.Game as IServer; var game = mob.Game as IGame; // It is not guaranteed that mob.Game will implement IServer. We are only guaranteed that it will implement IGame. if (server == null) { throw new NullReferenceException("LoginState can only be set to a player object that is part of a server."); } //Output the game information mob.Send(new InformationalMessage(game.Name)); mob.Send(new InformationalMessage(game.Description)); mob.Send(new InformationalMessage(string.Empty)); //blank line //Output the server MOTD information mob.Send(new InformationalMessage(string.Join("\n", server.MessageOfTheDay))); mob.Send(new InformationalMessage(string.Empty)); //blank line mob.StateManager.SwitchState(new LoginState()); } /// <summary> /// Gets the command. /// </summary> /// <param name="message">The message.</param> /// <returns>Returns no operation required.</returns> public Commands.ICommand GetCommand(IMessage message) { return new NoOpCommand(); } /// <summary> /// Cleanups this instance during a state change. /// </summary> public void Cleanup() { // We have nothing to clean up. return; } } With the way that I have my FSM set up at the moment, the user can only ever have one state at a time. I read a few different posts on here about state management but nothing regarding keeping a stack history. I thought about using a Stack collection, and just pushing new states on to the stack then popping them off as the user moves out from one. It seems like it would work, but I'm not sure if it is the best approach to take. I'm looking for recommendations on this. I'm currently swapping state from within the individual states themselves as well which I'm on the fence about if it makes sense to do there or not. The user enters a command, the StateManager passes the command to the current State and lets it determine if it needs it (like passing in a password after entering a user name), if the state doesn't need any further commands, it returns null. If it does need to continue doing work, it returns a No Operation to let the state manager know that the state still requires further input from the user. If null is returned, the state manager will then go find the appropriate state for the command entered by the user. Example state requiring additional input from the user public class LoginState : IState { /// <summary> /// The connected player /// </summary> private IPlayer connectedPlayer; private enum CurrentState { FetchUserName, FetchPassword, InvalidUser, } private CurrentState currentState; /// <summary> /// Renders the current state to the players terminal. /// </summary> /// <param name="mob"></param> /// <exception cref="System.NullReferenceException"> /// ConnectState can only be used with a player object implementing IPlayer /// or /// LoginState can only be set to a player object that is part of a server. /// </exception> public void Render(IMob mob) { if (!(mob is IPlayer)) { throw new NullReferenceException("ConnectState can only be used with a player object implementing IPlayer"); } //Store a reference for the GetCommand() method to use. this.connectedPlayer = mob as IPlayer; var server = mob.Game as IServer; // Register to receive new input from the user. mob.ReceivedMessage += connectedPlayer_ReceivedMessage; if (server == null) { throw new NullReferenceException("LoginState can only be set to a player object that is part of a server."); } this.currentState = CurrentState.FetchUserName; switch (this.currentState) { case CurrentState.FetchUserName: mob.Send(new InputMessage("Please enter your user name")); break; case CurrentState.FetchPassword: mob.Send(new InputMessage("Please enter your password")); break; case CurrentState.InvalidUser: mob.Send(new InformationalMessage("Invalid username/password specified.")); this.currentState = CurrentState.FetchUserName; mob.Send(new InputMessage("Please enter your user name")); break; } } /// <summary> /// Receives the players input. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> void connectedPlayer_ReceivedMessage(object sender, IMessage e) { // Be good memory citizens and clean ourself up after receiving a message. // Not doing this results in duplicate events being registered and memory leaks. this.connectedPlayer.ReceivedMessage -= connectedPlayer_ReceivedMessage; ICommand command = this.GetCommand(e); } /// <summary> /// Gets the Command that the player entered and preps it for execution. /// </summary> /// <param name="command"></param> /// <returns>Returns the ICommand specified.</returns> public Commands.ICommand GetCommand(IMessage command) { if (this.currentState == CurrentState.FetchUserName) { this.connectedPlayer.Name = command.Message; this.currentState = CurrentState.FetchPassword; } else if (this.currentState == CurrentState.FetchPassword) { // find user } return new NoOpCommand(); } /// <summary> /// Cleanups this instance during a state change. /// </summary> public void Cleanup() { // If we have a player instance, we clean up the registered event. if (this.connectedPlayer != null) { this.connectedPlayer.ReceivedMessage -= this.connectedPlayer_ReceivedMessage; } } Maybe my entire FSM isn't wired up in the best way, but I would appreciate input on what would be the best to maintain a stack of state in a MUD game engine, and if my states should be allowed to receive the input from the user or not to check what command was entered before allowing the state manager to switch states. Thanks in advance.

    Read the article

  • Are XML Comments Necessary Documentation?

    - by Bob Horn
    I used to be a fan of requiring XML comments for documentation. I've since changed my mind for two main reasons: Like good code, methods should be self-explanatory. In practice, most XML comments are useless noise that provide no additional value. Many times we simply use GhostDoc to generate generic comments, and this is what I mean by useless noise: /// <summary> /// Gets or sets the unit of measure. /// </summary> /// <value> /// The unit of measure. /// </value> public string UnitOfMeasure { get; set; } To me, that's obvious. Having said that, if there were special instructions to include, then we should absolutely use XML comments. I like this excerpt from this article: Sometimes, you will need to write comments. But, it should be the exception not the rule. Comments should only be used when they are expressing something that cannot be expressed in code. If you want to write elegant code, strive to eliminate comments and instead write self-documenting code. Am I wrong to think we should only be using XML comments when the code isn't enough to explain itself on its own? I believe this is a good example where XML comments make pretty code look ugly. It takes a class like this... public class RawMaterialLabel : EntityBase { public long Id { get; set; } public string ManufacturerId { get; set; } public string PartNumber { get; set; } public string Quantity { get; set; } public string UnitOfMeasure { get; set; } public string LotNumber { get; set; } public string SublotNumber { get; set; } public int LabelSerialNumber { get; set; } public string PurchaseOrderNumber { get; set; } public string PurchaseOrderLineNumber { get; set; } public DateTime ManufacturingDate { get; set; } public string LastModifiedUser { get; set; } public DateTime LastModifiedTime { get; set; } public Binary VersionNumber { get; set; } public ICollection<LotEquipmentScan> LotEquipmentScans { get; private set; } } ... And turns it into this: /// <summary> /// Container for properties of a raw material label /// </summary> public class RawMaterialLabel : EntityBase { /// <summary> /// Gets or sets the id. /// </summary> /// <value> /// The id. /// </value> public long Id { get; set; } /// <summary> /// Gets or sets the manufacturer id. /// </summary> /// <value> /// The manufacturer id. /// </value> public string ManufacturerId { get; set; } /// <summary> /// Gets or sets the part number. /// </summary> /// <value> /// The part number. /// </value> public string PartNumber { get; set; } /// <summary> /// Gets or sets the quantity. /// </summary> /// <value> /// The quantity. /// </value> public string Quantity { get; set; } /// <summary> /// Gets or sets the unit of measure. /// </summary> /// <value> /// The unit of measure. /// </value> public string UnitOfMeasure { get; set; } /// <summary> /// Gets or sets the lot number. /// </summary> /// <value> /// The lot number. /// </value> public string LotNumber { get; set; } /// <summary> /// Gets or sets the sublot number. /// </summary> /// <value> /// The sublot number. /// </value> public string SublotNumber { get; set; } /// <summary> /// Gets or sets the label serial number. /// </summary> /// <value> /// The label serial number. /// </value> public int LabelSerialNumber { get; set; } /// <summary> /// Gets or sets the purchase order number. /// </summary> /// <value> /// The purchase order number. /// </value> public string PurchaseOrderNumber { get; set; } /// <summary> /// Gets or sets the purchase order line number. /// </summary> /// <value> /// The purchase order line number. /// </value> public string PurchaseOrderLineNumber { get; set; } /// <summary> /// Gets or sets the manufacturing date. /// </summary> /// <value> /// The manufacturing date. /// </value> public DateTime ManufacturingDate { get; set; } /// <summary> /// Gets or sets the last modified user. /// </summary> /// <value> /// The last modified user. /// </value> public string LastModifiedUser { get; set; } /// <summary> /// Gets or sets the last modified time. /// </summary> /// <value> /// The last modified time. /// </value> public DateTime LastModifiedTime { get; set; } /// <summary> /// Gets or sets the version number. /// </summary> /// <value> /// The version number. /// </value> public Binary VersionNumber { get; set; } /// <summary> /// Gets the lot equipment scans. /// </summary> /// <value> /// The lot equipment scans. /// </value> public ICollection<LotEquipmentScan> LotEquipmentScans { get; private set; } }

    Read the article

  • How do I create a VBA macro that will copy data from an entry sheet, into a summary sheet by date

    - by Mukkman
    I'm trying to create a macro that will copy data from a data entry sheet into a summary sheet. The entry sheet is going to be cleared daily so I can't use a formula just to reference it. I want the user to be able to enter a date, run a macro, and have the macro copy the data from the entry sheet into the cells for the corresponding date on the summary sheet. I've looked around and found bits and pieces of how to do this but I can't put it all together. Update: Thanks to the information below I was able to find some additional data. I have a pretty crude macro that works if the user manually selects the correct cell. Now I just need to figure out how to automatically select the current cell relative to the current date. Sub Update_Deposits() ' ' Update_Deposits Macro ' Dim selectedDate As String Dim rangeFound As Range selectedDate = Sheets("Summary Sheet").Range("F3") Set rangeFound = Sheets("Deposits").Cells.Find(CDate(selectedDate)) Dim Total1 As Double Dim Total2 As Double Dim Total3 As Double Dim Total4 As Double Dim Total5 As Double Total1 = Sheets("Summary Sheet").Range("E6") Total2 = Sheets("Summary Sheet").Range("E7") Total3 = Sheets("Summary Sheet").Range("E8") Total4 = Sheets("Summary Sheet").Range("E9") Total5 = Sheets("Summary Sheet").Range("E10") If Not (rangeFound Is Nothing) Then rangeFound.Offset(0, 2) = Total1 rangeFound.Offset(0, 3) = Total2 rangeFound.Offset(0, 4) = Total3 rangeFound.Offset(0, 6) = Total4 rangeFound.Offset(0, 7) = Total5 End If ' End Sub This version will find the first value on the page and fill in values: Sub Update_Deposits() ' ' Update_Deposits Macro ' Dim selectedDate As String Dim rangeFound As Range selectedDate = Sheets("Summary Sheet").Range("F3") Set rangeFound = Sheets("Deposits").Cells.Find(CDate(selectedDate)) Dim Total1 As Double Dim Total2 As Double Dim Total3 As Double Dim Total4 As Double Dim Total5 As Double Total1 = Sheets("Summary Sheet").Range("E6") Total2 = Sheets("Summary Sheet").Range("E7") Total3 = Sheets("Summary Sheet").Range("E8") Total4 = Sheets("Summary Sheet").Range("E9") Total5 = Sheets("Summary Sheet").Range("E10") If Not (rangeFound Is Nothing) Then rangeFound.Offset(0, 2) = Total1 rangeFound.Offset(0, 3) = Total2 rangeFound.Offset(0, 4) = Total3 rangeFound.Offset(0, 6) = Total4 rangeFound.Offset(0, 7) = Total5 End If ' End Sub

    Read the article

  • My Body Summary template for Orchard

    - by Bertrand Le Roy
    By default, when Orchard displays a content item such as a blog post in a list, it uses a very basic summary template that removes all markup and then extracts the first 200 characters. Removing the markup has the unfortunate effect of removing all styles and images, in particular the image I like to add to the beginning of my posts. Fortunately, overriding templates in Orchard is a piece of cake. Here is the Common.Body.Summary.cshtml file that I drop into the Views/Parts folder of pretty much all Orchard themes I build: @{ Orchard.ContentManagement.ContentItem contentItem = Model.ContentPart.ContentItem; var bodyHtml = Model.Html.ToString(); var more = bodyHtml.IndexOf("<!--more-->"); if (more != -1) { bodyHtml = bodyHtml.Substring(0, more); } else { var firstP = bodyHtml.IndexOf("<p>"); var firstSlashP = bodyHtml.IndexOf("</p>"); if (firstP >=0 && firstSlashP > firstP) { bodyHtml = bodyHtml.Substring(firstP, firstSlashP + 4 - firstP); } } var body = new HtmlString(bodyHtml); } <p>@body</p> <p>@Html.ItemDisplayLink(T("Read more...").ToString(), contentItem)</p> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This template does not remove any tags, but instead looks for an HTML comment delimiting the end of the post’s intro: <!--more--> This is the same convention that is being used in WordPress, and it’s easy to add from the source view in TinyMCE or Live Writer. If such a comment is not found, the template will extract the first paragraph (delimited by <p> and </p> tags) as the summary. And if it finds neither, it will use the whole post. The template also adds a localizable link to the full post.

    Read the article

  • ARM TechCon 2013: Oracle Summary from Henrik Stahl

    - by hinkmond
    Henrik Stahl posted a good blog post summary of Oracle's involvement at last week's ARM TechCon 2013 in Santa Clara, Calif. Lots of new and interesting items to note from this year's conference. See: ARM TechCon 2013 Summary Here's a quote: If you have been following Java news, you are already aware of the fact that there has been a lot of investment in Java for ARM-based devices and servers over the last couple of years... Good stuff related to Java Embedded on ARM chips, but even better stuff coming soon... Stay tuned. Hinkmond

    Read the article

  • Hosting the Razor Engine for Templating in Non-Web Applications

    - by Rick Strahl
    Microsoft’s new Razor HTML Rendering Engine that is currently shipping with ASP.NET MVC previews can be used outside of ASP.NET. Razor is an alternative view engine that can be used instead of the ASP.NET Page engine that currently works with ASP.NET WebForms and MVC. It provides a simpler and more readable markup syntax and is much more light weight in terms of functionality than the full blown WebForms Page engine, focusing only on features that are more along the lines of a pure view engine (or classic ASP!) with focus on expression and code rendering rather than a complex control/object model. Like the Page engine though, the parser understands .NET code syntax which can be embedded into templates, and behind the scenes the engine compiles markup and script code into an executing piece of .NET code in an assembly. Although it ships as part of the ASP.NET MVC and WebMatrix the Razor Engine itself is not directly dependent on ASP.NET or IIS or HTTP in any way. And although there are some markup and rendering features that are optimized for HTML based output generation, Razor is essentially a free standing template engine. And what’s really nice is that unlike the ASP.NET Runtime, Razor is fairly easy to host inside of your own non-Web applications to provide templating functionality. Templating in non-Web Applications? Yes please! So why might you host a template engine in your non-Web application? Template rendering is useful in many places and I have a number of applications that make heavy use of it. One of my applications – West Wind Html Help Builder - exclusively uses template based rendering to merge user supplied help text content into customizable and executable HTML markup templates that provide HTML output for CHM style HTML Help. This is an older product and it’s not actually using .NET at the moment – and this is one reason I’m looking at Razor for script hosting at the moment. For a few .NET applications though I’ve actually used the ASP.NET Runtime hosting to provide templating and mail merge style functionality and while that works reasonably well it’s a very heavy handed approach. It’s very resource intensive and has potential issues with versioning in various different versions of .NET. The generic implementation I created in the article above requires a lot of fix up to mimic an HTTP request in a non-HTTP environment and there are a lot of little things that have to happen to ensure that the ASP.NET runtime works properly most of it having nothing to do with the templating aspect but just satisfying ASP.NET’s requirements. The Razor Engine on the other hand is fairly light weight and completely decoupled from the ASP.NET runtime and the HTTP processing. Rather it’s a pure template engine whose sole purpose is to render text templates. Hosting this engine in your own applications can be accomplished with a reasonable amount of code (actually just a few lines with the tools I’m about to describe) and without having to fake HTTP requests. It’s also much lighter on resource usage and you can easily attach custom properties to your base template implementation to easily pass context from the parent application into templates all of which was rather complicated with ASP.NET runtime hosting. Installing the Razor Template Engine You can get Razor as part of the MVC 3 (RC and later) or Web Matrix. Both are available as downloadable components from the Web Platform Installer Version 3.0 (!important – V2 doesn’t show these components). If you already have that version of the WPI installed just fire it up. You can get the latest version of the Web Platform Installer from here: http://www.microsoft.com/web/gallery/install.aspx Once the platform Installer 3.0 is installed install either MVC 3 or ASP.NET Web Pages. Once installed you’ll find a System.Web.Razor assembly in C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.Razor.dll which you can add as a reference to your project. Creating a Wrapper The basic Razor Hosting API is pretty simple and you can host Razor with a (large-ish) handful of lines of code. I’ll show the basics of it later in this article. However, if you want to customize the rendering and handle assembly and namespace includes for the markup as well as deal with text and file inputs as well as forcing Razor to run in a separate AppDomain so you can unload the code-generated assemblies and deal with assembly caching for re-used templates little more work is required to create something that is more easily reusable. For this reason I created a Razor Hosting wrapper project that combines a bunch of this functionality into an easy to use hosting class, a hosting factory that can load the engine in a separate AppDomain and a couple of hosting containers that provided folder based and string based caching for templates for an easily embeddable and reusable engine with easy to use syntax. If you just want the code and play with the samples and source go grab the latest code from the Subversion Repository at: http://www.west-wind.com:8080/svn/articles/trunk/RazorHosting/ or a snapshot from: http://www.west-wind.com/files/tools/RazorHosting.zip Getting Started Before I get into how hosting with Razor works, let’s take a look at how you can get up and running quickly with the wrapper classes provided. It only takes a few lines of code. The easiest way to use these Razor Hosting Wrappers is to use one of the two HostContainers provided. One is for hosting Razor scripts in a directory and rendering them as relative paths from these script files on disk. The other HostContainer serves razor scripts from string templates… Let’s start with a very simple template that displays some simple expressions, some code blocks and demonstrates rendering some data from contextual data that you pass to the template in the form of a ‘context’. Here’s a simple Razor template: @using System.Reflection Hello @Context.FirstName! Your entry was entered on: @Context.Entered @{ // Code block: Update the host Windows Form passed in through the context Context.WinForm.Text = "Hello World from Razor at " + DateTime.Now.ToString(); } AppDomain Id: @AppDomain.CurrentDomain.FriendlyName Assembly: @Assembly.GetExecutingAssembly().FullName Code based output: @{ // Write output with Response object from code string output = string.Empty; for (int i = 0; i < 10; i++) { output += i.ToString() + " "; } Response.Write(output); } Pretty easy to see what’s going on here. The only unusual thing in this code is the Context object which is an arbitrary object I’m passing from the host to the template by way of the template base class. I’m also displaying the current AppDomain and the executing Assembly name so you can see how compiling and running a template actually loads up new assemblies. Also note that as part of my context I’m passing a reference to the current Windows Form down to the template and changing the title from within the script. It’s a silly example, but it demonstrates two-way communication between host and template and back which can be very powerful. The easiest way to quickly render this template is to use the RazorEngine<TTemplateBase> class. The generic parameter specifies a template base class type that is used by Razor internally to generate the class it generates from a template. The default implementation provided in my RazorHosting wrapper is RazorTemplateBase. Here’s a simple one that renders from a string and outputs a string: var engine = new RazorEngine<RazorTemplateBase>(); // we can pass any object as context - here create a custom context var context = new CustomContext() { WinForm = this, FirstName = "Rick", Entered = DateTime.Now.AddDays(-10) }; string output = engine.RenderTemplate(this.txtSource.Text new string[] { "System.Windows.Forms.dll" }, context); if (output == null) this.txtResult.Text = "*** ERROR:\r\n" + engine.ErrorMessage; else this.txtResult.Text = output; Simple enough. This code renders a template from a string input and returns a result back as a string. It  creates a custom context and passes that to the template which can then access the Context’s properties. Note that anything passed as ‘context’ must be serializable (or MarshalByRefObject) – otherwise you get an exception when passing the reference over AppDomain boundaries (discussed later). Passing a context is optional, but is a key feature in being able to share data between the host application and the template. Note that we use the Context object to access FirstName, Entered and even the host Windows Form object which is used in the template to change the Window caption from within the script! In the code above all the work happens in the RenderTemplate method which provide a variety of overloads to read and write to and from strings, files and TextReaders/Writers. Here’s another example that renders from a file input using a TextReader: using (reader = new StreamReader("templates\\simple.csHtml", true)) { result = host.RenderTemplate(reader, new string[] { "System.Windows.Forms.dll" }, this.CustomContext); } RenderTemplate() is fairly high level and it handles loading of the runtime, compiling into an assembly and rendering of the template. If you want more control you can use the lower level methods to control each step of the way which is important for the HostContainers I’ll discuss later. Basically for those scenarios you want to separate out loading of the engine, compiling into an assembly and then rendering the template from the assembly. Why? So we can keep assemblies cached. In the code above a new assembly is created for each template rendered which is inefficient and uses up resources. Depending on the size of your templates and how often you fire them you can chew through memory very quickly. This slighter lower level approach is only a couple of extra steps: // we can pass any object as context - here create a custom context var context = new CustomContext() { WinForm = this, FirstName = "Rick", Entered = DateTime.Now.AddDays(-10) }; var engine = new RazorEngine<RazorTemplateBase>(); string assId = null; using (StringReader reader = new StringReader(this.txtSource.Text)) { assId = engine.ParseAndCompileTemplate(new string[] { "System.Windows.Forms.dll" }, reader); } string output = engine.RenderTemplateFromAssembly(assId, context); if (output == null) this.txtResult.Text = "*** ERROR:\r\n" + engine.ErrorMessage; else this.txtResult.Text = output; The difference here is that you can capture the assembly – or rather an Id to it – and potentially hold on to it to render again later assuming the template hasn’t changed. The HostContainers take advantage of this feature to cache the assemblies based on certain criteria like a filename and file time step or a string hash that if not change indicate that an assembly can be reused. Note that ParseAndCompileTemplate returns an assembly Id rather than the assembly itself. This is done so that that the assembly always stays in the host’s AppDomain and is not passed across AppDomain boundaries which would cause load failures. We’ll talk more about this in a minute but for now just realize that assemblies references are stored in a list and are accessible by this ID to allow locating and re-executing of the assembly based on that id. Reuse of the assembly avoids recompilation overhead and creation of yet another assembly that loads into the current AppDomain. You can play around with several different versions of the above code in the main sample form:   Using Hosting Containers for more Control and Caching The above examples simply render templates into assemblies each and every time they are executed. While this works and is even reasonably fast, it’s not terribly efficient. If you render templates more than once it would be nice if you could cache the generated assemblies for example to avoid re-compiling and creating of a new assembly each time. Additionally it would be nice to load template assemblies into a separate AppDomain optionally to be able to be able to unload assembli es and also to protect your host application from scripting attacks with malicious template code. Hosting containers provide also provide a wrapper around the RazorEngine<T> instance, a factory (which allows creation in separate AppDomains) and an easy way to start and stop the container ‘runtime’. The Razor Hosting samples provide two hosting containers: RazorFolderHostContainer and StringHostContainer. The folder host provides a simple runtime environment for a folder structure similar in the way that the ASP.NET runtime handles a virtual directory as it’s ‘application' root. Templates are loaded from disk in relative paths and the resulting assemblies are cached unless the template on disk is changed. The string host also caches templates based on string hashes – if the same string is passed a second time a cached version of the assembly is used. Here’s how HostContainers work. I’ll use the FolderHostContainer because it’s likely the most common way you’d use templates – from disk based templates that can be easily edited and maintained on disk. The first step is to create an instance of it and keep it around somewhere (in the example it’s attached as a property to the Form): RazorFolderHostContainer Host = new RazorFolderHostContainer(); public RazorFolderHostForm() { InitializeComponent(); // The base path for templates - templates are rendered with relative paths // based on this path. Host.TemplatePath = Path.Combine(Environment.CurrentDirectory, TemplateBaseFolder); // Add any assemblies you want reference in your templates Host.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // Start up the host container Host.Start(); } Next anytime you want to render a template you can use simple code like this: private void RenderTemplate(string fileName) { // Pass the template path via the Context var relativePath = Utilities.GetRelativePath(fileName, Host.TemplatePath); if (!Host.RenderTemplate(relativePath, this.Context, Host.RenderingOutputFile)) { MessageBox.Show("Error: " + Host.ErrorMessage); return; } this.webBrowser1.Navigate("file://" + Host.RenderingOutputFile); } You can also render the output to a string instead of to a file: string result = Host.RenderTemplateToString(relativePath,context); Finally if you want to release the engine and shut down the hosting AppDomain you can simply do: Host.Stop(); Stopping the AppDomain and restarting it (ie. calling Stop(); followed by Start()) is also a nice way to release all resources in the AppDomain. The FolderBased domain also supports partial Rendering based on root path based relative paths with the same caching characteristics as the main templates. From within a template you can call out to a partial like this: @RenderPartial(@"partials\PartialRendering.cshtml", Context) where partials\PartialRendering.cshtml is a relative to the template root folder. The folder host example lets you load up templates from disk and display the result in a Web Browser control which demonstrates using Razor HTML output from templates that contain HTML syntax which happens to me my target scenario for Html Help Builder.   The Razor Engine Wrapper Project The project I created to wrap Razor hosting has a fair bit of code and a number of classes associated with it. Most of the components are internally used and as you can see using the final RazorEngine<T> and HostContainer classes is pretty easy. The classes are extensible and I suspect developers will want to build more customized host containers for their applications. Host containers are the key to wrapping up all functionality – Engine, BaseTemplate, AppDomain Hosting, Caching etc in a logical piece that is ready to be plugged into an application. When looking at the code there are a couple of core features provided: Core Razor Engine Hosting This is the core Razor hosting which provides the basics of loading a template, compiling it into an assembly and executing it. This is fairly straightforward, but without a host container that can cache assemblies based on some criteria templates are recompiled and re-created each time which is inefficient (although pretty fast). The base engine wrapper implementation also supports hosting the Razor runtime in a separate AppDomain for security and the ability to unload it on demand. Host Containers The engine hosting itself doesn’t provide any sort of ‘runtime’ service like picking up files from disk, caching assemblies and so forth. So my implementation provides two HostContainers: RazorFolderHostContainer and RazorStringHostContainer. The FolderHost works off a base directory and loads templates based on relative paths (sort of like the ASP.NET runtime does off a virtual). The HostContainers also deal with caching of template assemblies – for the folder host the file date is tracked and checked for updates and unless the template is changed a cached assembly is reused. The StringHostContainer similiarily checks string hashes to figure out whether a particular string template was previously compiled and executed. The HostContainers also act as a simple startup environment and a single reference to easily store and reuse in an application. TemplateBase Classes The template base classes are the base classes that from which the Razor engine generates .NET code. A template is parsed into a class with an Execute() method and the class is based on this template type you can specify. RazorEngine<TBaseTemplate> can receive this type and the HostContainers default to specific templates in their base implementations. Template classes are customizable to allow you to create templates that provide application specific features and interaction from the template to your host application. How does the RazorEngine wrapper work? You can browse the source code in the links above or in the repository or download the source, but I’ll highlight some key features here. Here’s part of the RazorEngine implementation that can be used to host the runtime and that demonstrates the key code required to host the Razor runtime. The RazorEngine class is implemented as a generic class to reflect the Template base class type: public class RazorEngine<TBaseTemplateType> : MarshalByRefObject where TBaseTemplateType : RazorTemplateBase The generic type is used to internally provide easier access to the template type and assignments on it as part of the template processing. The class also inherits MarshalByRefObject to allow execution over AppDomain boundaries – something that all the classes discussed here need to do since there is much interaction between the host and the template. The first two key methods deal with creating a template assembly: /// <summary> /// Creates an instance of the RazorHost with various options applied. /// Applies basic namespace imports and the name of the class to generate /// </summary> /// <param name="generatedNamespace"></param> /// <param name="generatedClass"></param> /// <returns></returns> protected RazorTemplateEngine CreateHost(string generatedNamespace, string generatedClass) { Type baseClassType = typeof(TBaseTemplateType); RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage()); host.DefaultBaseClass = baseClassType.FullName; host.DefaultClassName = generatedClass; host.DefaultNamespace = generatedNamespace; host.NamespaceImports.Add("System"); host.NamespaceImports.Add("System.Text"); host.NamespaceImports.Add("System.Collections.Generic"); host.NamespaceImports.Add("System.Linq"); host.NamespaceImports.Add("System.IO"); return new RazorTemplateEngine(host); } /// <summary> /// Parses and compiles a markup template into an assembly and returns /// an assembly name. The name is an ID that can be passed to /// ExecuteTemplateByAssembly which picks up a cached instance of the /// loaded assembly. /// /// </summary> /// <param name="namespaceOfGeneratedClass">The namespace of the class to generate from the template</param> /// <param name="generatedClassName">The name of the class to generate from the template</param> /// <param name="ReferencedAssemblies">Any referenced assemblies by dll name only. Assemblies must be in execution path of host or in GAC.</param> /// <param name="templateSourceReader">Textreader that loads the template</param> /// <remarks> /// The actual assembly isn't returned here to allow for cross-AppDomain /// operation. If the assembly was returned it would fail for cross-AppDomain /// calls. /// </remarks> /// <returns>An assembly Id. The Assembly is cached in memory and can be used with RenderFromAssembly.</returns> public string ParseAndCompileTemplate( string namespaceOfGeneratedClass, string generatedClassName, string[] ReferencedAssemblies, TextReader templateSourceReader) { RazorTemplateEngine engine = CreateHost(namespaceOfGeneratedClass, generatedClassName); // Generate the template class as CodeDom GeneratorResults razorResults = engine.GenerateCode(templateSourceReader); // Create code from the codeDom and compile CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeGeneratorOptions options = new CodeGeneratorOptions(); // Capture Code Generated as a string for error info // and debugging LastGeneratedCode = null; using (StringWriter writer = new StringWriter()) { codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options); LastGeneratedCode = writer.ToString(); } CompilerParameters compilerParameters = new CompilerParameters(ReferencedAssemblies); // Standard Assembly References compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); // dynamic support! // Also add the current assembly so RazorTemplateBase is available compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8)); compilerParameters.GenerateInMemory = Configuration.CompileToMemory; if (!Configuration.CompileToMemory) compilerParameters.OutputAssembly = Path.Combine(Configuration.TempAssemblyPath, "_" + Guid.NewGuid().ToString("n") + ".dll"); CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode); if (compilerResults.Errors.Count > 0) { var compileErrors = new StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors) compileErrors.Append(String.Format(Resources.LineX0TColX1TErrorX2RN, compileError.Line, compileError.Column, compileError.ErrorText)); this.SetError(compileErrors.ToString() + "\r\n" + LastGeneratedCode); return null; } AssemblyCache.Add(compilerResults.CompiledAssembly.FullName, compilerResults.CompiledAssembly); return compilerResults.CompiledAssembly.FullName; } Think of the internal CreateHost() method as setting up the assembly generated from each template. Each template compiles into a separate assembly. It sets up namespaces, and assembly references, the base class used and the name and namespace for the generated class. ParseAndCompileTemplate() then calls the CreateHost() method to receive the template engine generator which effectively generates a CodeDom from the template – the template is turned into .NET code. The code generated from our earlier example looks something like this: //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RazorTest { using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.IO; using System.Reflection; public class RazorTemplate : RazorHosting.RazorTemplateBase { #line hidden public RazorTemplate() { } public override void Execute() { WriteLiteral("Hello "); Write(Context.FirstName); WriteLiteral("! Your entry was entered on: "); Write(Context.Entered); WriteLiteral("\r\n\r\n"); // Code block: Update the host Windows Form passed in through the context Context.WinForm.Text = "Hello World from Razor at " + DateTime.Now.ToString(); WriteLiteral("\r\nAppDomain Id:\r\n "); Write(AppDomain.CurrentDomain.FriendlyName); WriteLiteral("\r\n \r\nAssembly:\r\n "); Write(Assembly.GetExecutingAssembly().FullName); WriteLiteral("\r\n\r\nCode based output: \r\n"); // Write output with Response object from code string output = string.Empty; for (int i = 0; i < 10; i++) { output += i.ToString() + " "; } } } } Basically the template’s body is turned into code in an Execute method that is called. Internally the template’s Write method is fired to actually generate the output. Note that the class inherits from RazorTemplateBase which is the generic parameter I used to specify the base class when creating an instance in my RazorEngine host: var engine = new RazorEngine<RazorTemplateBase>(); This template class must be provided and it must implement an Execute() and Write() method. Beyond that you can create any class you chose and attach your own properties. My RazorTemplateBase class implementation is very simple: public class RazorTemplateBase : MarshalByRefObject, IDisposable { /// <summary> /// You can pass in a generic context object /// to use in your template code /// </summary> public dynamic Context { get; set; } /// <summary> /// Class that generates output. Currently ultra simple /// with only Response.Write() implementation. /// </summary> public RazorResponse Response { get; set; } public object HostContainer {get; set; } public object Engine { get; set; } public RazorTemplateBase() { Response = new RazorResponse(); } public virtual void Write(object value) { Response.Write(value); } public virtual void WriteLiteral(object value) { Response.Write(value); } /// <summary> /// Razor Parser implements this method /// </summary> public virtual void Execute() {} public virtual void Dispose() { if (Response != null) { Response.Dispose(); Response = null; } } } Razor fills in the Execute method when it generates its subclass and uses the Write() method to output content. As you can see I use a RazorResponse() class here to generate output. This isn’t necessary really, as you could use a StringBuilder or StringWriter() directly, but I prefer using Response object so I can extend the Response behavior as needed. The RazorResponse class is also very simple and merely acts as a wrapper around a TextWriter: public class RazorResponse : IDisposable { /// <summary> /// Internal text writer - default to StringWriter() /// </summary> public TextWriter Writer = new StringWriter(); public virtual void Write(object value) { Writer.Write(value); } public virtual void WriteLine(object value) { Write(value); Write("\r\n"); } public virtual void WriteFormat(string format, params object[] args) { Write(string.Format(format, args)); } public override string ToString() { return Writer.ToString(); } public virtual void Dispose() { Writer.Close(); } public virtual void SetTextWriter(TextWriter writer) { // Close original writer if (Writer != null) Writer.Close(); Writer = writer; } } The Rendering Methods of RazorEngine At this point I’ve talked about the assembly generation logic and the template implementation itself. What’s left is that once you’ve generated the assembly is to execute it. The code to do this is handled in the various RenderXXX methods of the RazorEngine class. Let’s look at the lowest level one of these which is RenderTemplateFromAssembly() and a couple of internal support methods that handle instantiating and invoking of the generated template method: public string RenderTemplateFromAssembly( string assemblyId, string generatedNamespace, string generatedClass, object context, TextWriter outputWriter) { this.SetError(); Assembly generatedAssembly = AssemblyCache[assemblyId]; if (generatedAssembly == null) { this.SetError(Resources.PreviouslyCompiledAssemblyNotFound); return null; } string className = generatedNamespace + "." + generatedClass; Type type; try { type = generatedAssembly.GetType(className); } catch (Exception ex) { this.SetError(Resources.UnableToCreateType + className + ": " + ex.Message); return null; } // Start with empty non-error response (if we use a writer) string result = string.Empty; using(TBaseTemplateType instance = InstantiateTemplateClass(type)) { if (instance == null) return null; if (outputWriter != null) instance.Response.SetTextWriter(outputWriter); if (!InvokeTemplateInstance(instance, context)) return null; // Capture string output if implemented and return // otherwise null is returned if (outputWriter == null) result = instance.Response.ToString(); } return result; } protected virtual TBaseTemplateType InstantiateTemplateClass(Type type) { TBaseTemplateType instance = Activator.CreateInstance(type) as TBaseTemplateType; if (instance == null) { SetError(Resources.CouldnTActivateTypeInstance + type.FullName); return null; } instance.Engine = this; // If a HostContainer was set pass that to the template too instance.HostContainer = this.HostContainer; return instance; } /// <summary> /// Internally executes an instance of the template, /// captures errors on execution and returns true or false /// </summary> /// <param name="instance">An instance of the generated template</param> /// <returns>true or false - check ErrorMessage for errors</returns> protected virtual bool InvokeTemplateInstance(TBaseTemplateType instance, object context) { try { instance.Context = context; instance.Execute(); } catch (Exception ex) { this.SetError(Resources.TemplateExecutionError + ex.Message); return false; } finally { // Must make sure Response is closed instance.Response.Dispose(); } return true; } The RenderTemplateFromAssembly method basically requires the namespace and class to instantate and creates an instance of the class using InstantiateTemplateClass(). It then invokes the method with InvokeTemplateInstance(). These two methods are broken out because they are re-used by various other rendering methods and also to allow subclassing and providing additional configuration tasks to set properties and pass values to templates at execution time. In the default mode instantiation sets the Engine and HostContainer (discussed later) so the template can call back into the template engine, and the context is set when the template method is invoked. The various RenderXXX methods use similar code although they create the assemblies first. If you’re after potentially cashing assemblies the method is the one to call and that’s exactly what the two HostContainer classes do. More on that in a minute, but before we get into HostContainers let’s talk about AppDomain hosting and the like. Running Templates in their own AppDomain With the RazorEngine class above, when a template is parsed into an assembly and executed the assembly is created (in memory or on disk – you can configure that) and cached in the current AppDomain. In .NET once an assembly has been loaded it can never be unloaded so if you’re loading lots of templates and at some time you want to release them there’s no way to do so. If however you load the assemblies in a separate AppDomain that new AppDomain can be unloaded and the assemblies loaded in it with it. In order to host the templates in a separate AppDomain the easiest thing to do is to run the entire RazorEngine in a separate AppDomain. Then all interaction occurs in the other AppDomain and no further changes have to be made. To facilitate this there is a RazorEngineFactory which has methods that can instantiate the RazorHost in a separate AppDomain as well as in the local AppDomain. The host creates the remote instance and then hangs on to it to keep it alive as well as providing methods to shut down the AppDomain and reload the engine. Sounds complicated but cross-AppDomain invocation is actually fairly easy to implement. Here’s some of the relevant code from the RazorEngineFactory class. Like the RazorEngine this class is generic and requires a template base type in the generic class name: public class RazorEngineFactory<TBaseTemplateType> where TBaseTemplateType : RazorTemplateBase Here are the key methods of interest: /// <summary> /// Creates an instance of the RazorHost in a new AppDomain. This /// version creates a static singleton that that is cached and you /// can call UnloadRazorHostInAppDomain to unload it. /// </summary> /// <returns></returns> public static RazorEngine<TBaseTemplateType> CreateRazorHostInAppDomain() { if (Current == null) Current = new RazorEngineFactory<TBaseTemplateType>(); return Current.GetRazorHostInAppDomain(); } public static void UnloadRazorHostInAppDomain() { if (Current != null) Current.UnloadHost(); Current = null; } /// <summary> /// Instance method that creates a RazorHost in a new AppDomain. /// This method requires that you keep the Factory around in /// order to keep the AppDomain alive and be able to unload it. /// </summary> /// <returns></returns> public RazorEngine<TBaseTemplateType> GetRazorHostInAppDomain() { LocalAppDomain = CreateAppDomain(null); if (LocalAppDomain == null) return null; /// Create the instance inside of the new AppDomain /// Note: remote domain uses local EXE's AppBasePath!!! RazorEngine<TBaseTemplateType> host = null; try { Assembly ass = Assembly.GetExecutingAssembly(); string AssemblyPath = ass.Location; host = (RazorEngine<TBaseTemplateType>) LocalAppDomain.CreateInstanceFrom(AssemblyPath, typeof(RazorEngine<TBaseTemplateType>).FullName).Unwrap(); } catch (Exception ex) { ErrorMessage = ex.Message; return null; } return host; } /// <summary> /// Internally creates a new AppDomain in which Razor templates can /// be run. /// </summary> /// <param name="appDomainName"></param> /// <returns></returns> private AppDomain CreateAppDomain(string appDomainName) { if (appDomainName == null) appDomainName = "RazorHost_" + Guid.NewGuid().ToString("n"); AppDomainSetup setup = new AppDomainSetup(); // *** Point at current directory setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain localDomain = AppDomain.CreateDomain(appDomainName, null, setup); return localDomain; } /// <summary> /// Allow unloading of the created AppDomain to release resources /// All internal resources in the AppDomain are released including /// in memory compiled Razor assemblies. /// </summary> public void UnloadHost() { if (this.LocalAppDomain != null) { AppDomain.Unload(this.LocalAppDomain); this.LocalAppDomain = null; } } The static CreateRazorHostInAppDomain() is the key method that startup code usually calls. It uses a Current singleton instance to an instance of itself that is created cross AppDomain and is kept alive because it’s static. GetRazorHostInAppDomain actually creates a cross-AppDomain instance which first creates a new AppDomain and then loads the RazorEngine into it. The remote Proxy instance is returned as a result to the method and can be used the same as a local instance. The code to run with a remote AppDomain is simple: private RazorEngine<RazorTemplateBase> CreateHost() { if (this.Host != null) return this.Host; // Use Static Methods - no error message if host doesn't load this.Host = RazorEngineFactory<RazorTemplateBase>.CreateRazorHostInAppDomain(); if (this.Host == null) { MessageBox.Show("Unable to load Razor Template Host", "Razor Hosting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return this.Host; } This code relies on a local reference of the Host which is kept around for the duration of the app (in this case a form reference). To use this you’d simply do: this.Host = CreateHost(); if (host == null) return; string result = host.RenderTemplate( this.txtSource.Text, new string[] { "System.Windows.Forms.dll", "Westwind.Utilities.dll" }, this.CustomContext); if (result == null) { MessageBox.Show(host.ErrorMessage, "Template Execution Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } this.txtResult.Text = result; Now all templates run in a remote AppDomain and can be unloaded with simple code like this: RazorEngineFactory<RazorTemplateBase>.UnloadRazorHostInAppDomain(); this.Host = null; One Step further – Providing a caching ‘Runtime’ Once we can load templates in a remote AppDomain we can add some additional functionality like assembly caching based on application specific features. One of my typical scenarios is to render templates out of a scripts folder. So all templates live in a folder and they change infrequently. So a Folder based host that can compile these templates once and then only recompile them if something changes would be ideal. Enter host containers which are basically wrappers around the RazorEngine<t> and RazorEngineFactory<t>. They provide additional logic for things like file caching based on changes on disk or string hashes for string based template inputs. The folder host also provides for partial rendering logic through a custom template base implementation. There’s a base implementation in RazorBaseHostContainer, which provides the basics for hosting a RazorEngine, which includes the ability to start and stop the engine, cache assemblies and add references: public abstract class RazorBaseHostContainer<TBaseTemplateType> : MarshalByRefObject where TBaseTemplateType : RazorTemplateBase, new() { public RazorBaseHostContainer() { UseAppDomain = true; GeneratedNamespace = "__RazorHost"; } /// <summary> /// Determines whether the Container hosts Razor /// in a separate AppDomain. Seperate AppDomain /// hosting allows unloading and releasing of /// resources. /// </summary> public bool UseAppDomain { get; set; } /// <summary> /// Base folder location where the AppDomain /// is hosted. By default uses the same folder /// as the host application. /// /// Determines where binary dependencies are /// found for assembly references. /// </summary> public string BaseBinaryFolder { get; set; } /// <summary> /// List of referenced assemblies as string values. /// Must be in GAC or in the current folder of the host app/ /// base BinaryFolder /// </summary> public List<string> ReferencedAssemblies = new List<string>(); /// <summary> /// Name of the generated namespace for template classes /// </summary> public string GeneratedNamespace {get; set; } /// <summary> /// Any error messages /// </summary> public string ErrorMessage { get; set; } /// <summary> /// Cached instance of the Host. Required to keep the /// reference to the host alive for multiple uses. /// </summary> public RazorEngine<TBaseTemplateType> Engine; /// <summary> /// Cached instance of the Host Factory - so we can unload /// the host and its associated AppDomain. /// </summary> protected RazorEngineFactory<TBaseTemplateType> EngineFactory; /// <summary> /// Keep track of each compiled assembly /// and when it was compiled. /// /// Use a hash of the string to identify string /// changes. /// </summary> protected Dictionary<int, CompiledAssemblyItem> LoadedAssemblies = new Dictionary<int, CompiledAssemblyItem>(); /// <summary> /// Call to start the Host running. Follow by a calls to RenderTemplate to /// render individual templates. Call Stop when done. /// </summary> /// <returns>true or false - check ErrorMessage on false </returns> public virtual bool Start() { if (Engine == null) { if (UseAppDomain) Engine = RazorEngineFactory<TBaseTemplateType>.CreateRazorHostInAppDomain(); else Engine = RazorEngineFactory<TBaseTemplateType>.CreateRazorHost(); Engine.Configuration.CompileToMemory = true; Engine.HostContainer = this; if (Engine == null) { this.ErrorMessage = EngineFactory.ErrorMessage; return false; } } return true; } /// <summary> /// Stops the Host and releases the host AppDomain and cached /// assemblies. /// </summary> /// <returns>true or false</returns> public bool Stop() { this.LoadedAssemblies.Clear(); RazorEngineFactory<RazorTemplateBase>.UnloadRazorHostInAppDomain(); this.Engine = null; return true; } … } This base class provides most of the mechanics to host the runtime, but no application specific implementation for rendering. There are rendering functions but they just call the engine directly and provide no caching – there’s no context to decide how to cache and reuse templates. The key methods are Start and Stop and their main purpose is to start a new AppDomain (optionally) and shut it down when requested. The RazorFolderHostContainer – Folder Based Runtime Hosting Let’s look at the more application specific RazorFolderHostContainer implementation which is defined like this: public class RazorFolderHostContainer : RazorBaseHostContainer<RazorTemplateFolderHost> Note that a customized RazorTemplateFolderHost class template is used for this implementation that supports partial rendering in form of a RenderPartial() method that’s available to templates. The folder host’s features are: Render templates based on a Template Base Path (a ‘virtual’ if you will) Cache compiled assemblies based on the relative path and file time stamp File changes on templates cause templates to be recompiled into new assemblies Support for partial rendering using base folder relative pathing As shown in the startup examples earlier host containers require some startup code with a HostContainer tied to a persistent property (like a Form property): // The base path for templates - templates are rendered with relative paths // based on this path. HostContainer.TemplatePath = Path.Combine(Environment.CurrentDirectory, TemplateBaseFolder); // Default output rendering disk location HostContainer.RenderingOutputFile = Path.Combine(HostContainer.TemplatePath, "__Preview.htm"); // Add any assemblies you want reference in your templates HostContainer.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // Start up the host container HostContainer.Start(); Once that’s done, you can render templates with the host container: // Pass the template path for full filename seleted with OpenFile Dialog // relativepath is: subdir\file.cshtml or file.cshtml or ..\file.cshtml var relativePath = Utilities.GetRelativePath(fileName, HostContainer.TemplatePath); if (!HostContainer.RenderTemplate(relativePath, Context, HostContainer.RenderingOutputFile)) { MessageBox.Show("Error: " + HostContainer.ErrorMessage); return; } webBrowser1.Navigate("file://" + HostContainer.RenderingOutputFile); The most critical task of the RazorFolderHostContainer implementation is to retrieve a template from disk, compile and cache it and then deal with deciding whether subsequent requests need to re-compile the template or simply use a cached version. Internally the GetAssemblyFromFileAndCache() handles this task: /// <summary> /// Internally checks if a cached assembly exists and if it does uses it /// else creates and compiles one. Returns an assembly Id to be /// used with the LoadedAssembly list. /// </summary> /// <param name="relativePath"></param> /// <param name="context"></param> /// <returns></returns> protected virtual CompiledAssemblyItem GetAssemblyFromFileAndCache(string relativePath) { string fileName = Path.Combine(TemplatePath, relativePath).ToLower(); int fileNameHash = fileName.GetHashCode(); if (!File.Exists(fileName)) { this.SetError(Resources.TemplateFileDoesnTExist + fileName); return null; } CompiledAssemblyItem item = null; this.LoadedAssemblies.TryGetValue(fileNameHash, out item); string assemblyId = null; // Check for cached instance if (item != null) { var fileTime = File.GetLastWriteTimeUtc(fileName); if (fileTime <= item.CompileTimeUtc) assemblyId = item.AssemblyId; } else item = new CompiledAssemblyItem(); // No cached instance - create assembly and cache if (assemblyId == null) { string safeClassName = GetSafeClassName(fileName); StreamReader reader = null; try { reader = new StreamReader(fileName, true); } catch (Exception ex) { this.SetError(Resources.ErrorReadingTemplateFile + fileName); return null; } assemblyId = Engine.ParseAndCompileTemplate(this.ReferencedAssemblies.ToArray(), reader); // need to ensure reader is closed if (reader != null) reader.Close(); if (assemblyId == null) { this.SetError(Engine.ErrorMessage); return null; } item.AssemblyId = assemblyId; item.CompileTimeUtc = DateTime.UtcNow; item.FileName = fileName; item.SafeClassName = safeClassName; this.LoadedAssemblies[fileNameHash] = item; } return item; } This code uses a LoadedAssembly dictionary which is comprised of a structure that holds a reference to a compiled assembly, a full filename and file timestamp and an assembly id. LoadedAssemblies (defined on the base class shown earlier) is essentially a cache for compiled assemblies and they are identified by a hash id. In the case of files the hash is a GetHashCode() from the full filename of the template. The template is checked for in the cache and if not found the file stamp is checked. If that’s newer than the cache’s compilation date the template is recompiled otherwise the version in the cache is used. All the core work defers to a RazorEngine<T> instance to ParseAndCompileTemplate(). The three rendering specific methods then are rather simple implementations with just a few lines of code dealing with parameter and return value parsing: /// <summary> /// Renders a template to a TextWriter. Useful to write output into a stream or /// the Response object. Used for partial rendering. /// </summary> /// <param name="relativePath">Relative path to the file in the folder structure</param> /// <param name="context">Optional context object or null</param> /// <param name="writer">The textwriter to write output into</param> /// <returns></returns> public bool RenderTemplate(string relativePath, object context, TextWriter writer) { // Set configuration data that is to be passed to the template (any object) Engine.TemplatePerRequestConfigurationData = new RazorFolderHostTemplateConfiguration() { TemplatePath = Path.Combine(this.TemplatePath, relativePath), TemplateRelativePath = relativePath, }; CompiledAssemblyItem item = GetAssemblyFromFileAndCache(relativePath); if (item == null) { writer.Close(); return false; } try { // String result will be empty as output will be rendered into the // Response object's stream output. However a null result denotes // an error string result = Engine.RenderTemplateFromAssembly(item.AssemblyId, context, writer); if (result == null) { this.SetError(Engine.ErrorMessage); return false; } } catch (Exception ex) { this.SetError(ex.Message); return false; } finally { writer.Close(); } return true; } /// <summary> /// Render a template from a source file on disk to a specified outputfile. /// </summary> /// <param name="relativePath">Relative path off the template root folder. Format: path/filename.cshtml</param> /// <param name="context">Any object that will be available in the template as a dynamic of this.Context</param> /// <param name="outputFile">Optional - output file where output is written to. If not specified the /// RenderingOutputFile property is used instead /// </param> /// <returns>true if rendering succeeds, false on failure - check ErrorMessage</returns> public bool RenderTemplate(string relativePath, object context, string outputFile) { if (outputFile == null) outputFile = RenderingOutputFile; try { using (StreamWriter writer = new StreamWriter(outputFile, false, Engine.Configuration.OutputEncoding, Engine.Configuration.StreamBufferSize)) { return RenderTemplate(relativePath, context, writer); } } catch (Exception ex) { this.SetError(ex.Message); return false; } return true; } /// <summary> /// Renders a template to string. Useful for RenderTemplate /// </summary> /// <param name="relativePath"></param> /// <param name="context"></param> /// <returns></returns> public string RenderTemplateToString(string relativePath, object context) { string result = string.Empty; try { using (StringWriter writer = new StringWriter()) { // String result will be empty as output will be rendered into the // Response object's stream output. However a null result denotes // an error if (!RenderTemplate(relativePath, context, writer)) { this.SetError(Engine.ErrorMessage); return null; } result = writer.ToString(); } } catch (Exception ex) { this.SetError(ex.Message); return null; } return result; } The idea is that you can create custom host container implementations that do exactly what you want fairly easily. Take a look at both the RazorFolderHostContainer and RazorStringHostContainer classes for the basic concepts you can use to create custom implementations. Notice also that you can set the engine’s PerRequestConfigurationData() from the host container: // Set configuration data that is to be passed to the template (any object) Engine.TemplatePerRequestConfigurationData = new RazorFolderHostTemplateConfiguration() { TemplatePath = Path.Combine(this.TemplatePath, relativePath), TemplateRelativePath = relativePath, }; which when set to a non-null value is passed to the Template’s InitializeTemplate() method. This method receives an object parameter which you can cast as needed: public override void InitializeTemplate(object configurationData) { // Pick up configuration data and stuff into Request object RazorFolderHostTemplateConfiguration config = configurationData as RazorFolderHostTemplateConfiguration; this.Request.TemplatePath = config.TemplatePath; this.Request.TemplateRelativePath = config.TemplateRelativePath; } With this data you can then configure any custom properties or objects on your main template class. It’s an easy way to pass data from the HostContainer all the way down into the template. The type you use is of type object so you have to cast it yourself, and it must be serializable since it will likely run in a separate AppDomain. This might seem like an ugly way to pass data around – normally I’d use an event delegate to call back from the engine to the host, but since this is running over AppDomain boundaries events get really tricky and passing a template instance back up into the host over AppDomain boundaries doesn’t work due to serialization issues. So it’s easier to pass the data from the host down into the template using this rather clumsy approach of set and forward. It’s ugly, but it’s something that can be hidden in the host container implementation as I’ve done here. It’s also not something you have to do in every implementation so this is kind of an edge case, but I know I’ll need to pass a bunch of data in some of my applications and this will be the easiest way to do so. Summing Up Hosting the Razor runtime is something I got jazzed up about quite a bit because I have an immediate need for this type of templating/merging/scripting capability in an application I’m working on. I’ve also been using templating in many apps and it’s always been a pain to deal with. The Razor engine makes this whole experience a lot cleaner and more light weight and with these wrappers I can now plug .NET based templating into my code literally with a few lines of code. That’s something to cheer about… I hope some of you will find this useful as well… Resources The examples and code require that you download the Razor runtimes. Projects are for Visual Studio 2010 running on .NET 4.0 Platform Installer 3.0 (install WebMatrix or MVC 3 for Razor Runtimes) Latest Code in Subversion Repository Download Snapshot of the Code Documentation (CHM Help File) © Rick Strahl, West Wind Technologies, 2005-2010Posted in ASP.NET  .NET  

    Read the article

  • how to change a button into a imagebutton in asp.net c#

    - by sweetsecret
    How to change the button into image button... the button in the beginning has "Pick a date" when clicked a calender pops out and the when a date is selected a label at the bottom reading the date comes in and the text on the button changes to disabled... i want to palce a imagebutton having a image icon of the calender and rest of the function will be the same.... the code as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % <%@ Register Assembly="EclipseWebSolutions.DatePicker" Namespace="EclipseWebSolutions.DatePicker" TagPrefix="ews" % Untitled Page       using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void DatePicker1_SelectionChanged(object sender, EventArgs e) { Label1.Text = DatePicker1.DateValue.ToShortDateString(); pnlLabel.Update(); } }

    Read the article

  • CodePlex Daily Summary for Friday, June 11, 2010

    CodePlex Daily Summary for Friday, June 11, 2010New ProjectsBIxPress Community Edition: SSIS Toolset BIDS Addin,Audit,Notify,Deploy,Template: BI xPress is a BIDS Addin/standalone application for SQL Developer/DBA. This tool has many features including Auditing, Notification, Deployment, P...C# Shell (cash): Cash is a command-line interpreter (shell), written in C#. It is part of an project to produce tools which replace the traditional GNU/Linux user-l...Chernarus Life Revivved: Chernarus life revivved for arma 2 multiplayerDKAL: DKAL is a distributed authorization policy language. This project contains an engine for running DKAL policies. It is implemented primarly in F#.ImageResizer for Albulle: Application permettant de déployer le contenu pour une la galerie photos php Albulle. L'objectif est de faciliter et automatiser le redimensionnem...Intraweb Active Directory Authentication Demo: A simple demo created using Delphi 7 and Intraweb 9.0.42 with the Active Directory Helper interface to authenticate a user to Active Directory. ...Lokad CQRS - build scalable web sites and enterprise solutions on Windows Azure: Lokad CQRS helps to build scalable cloud applications for Windows Azure. It provides time-proven guidance and .NET Application Blocks to help arc...LRS: Write a concise, reader-focused summary. Write a concise, reader-focused summary. Write a concise, reader-focused summary. ManagementPeople99: ...MEDILIG - MEDICAL LIFE GUARD: Cross-platform EHR/EMR software for the design, implementation and use of autonomous, open database models for multilingual clinical data managemen...NETris - ASP .NET, AJAX, Web Service based Tetris Game: Tetris game with business logic provided via Web Services.Peace Through Force: Peace Through Force is a 2D side scrolling tactical shooter developed in XNA Game Studio 3.1 using C#. The game is targeted to be made available o...Powwa: Util to show battery status and cpu speed on laptop. Uses jWMI's for interfacing with Windows' WMI.Resource Management System: Resource Management system for Internal purpose using WPF,WCF and SilverlighttChat - ASP.NET, Ajax & Web Service based Chat Room: Simple chat room application. Technology: ASP .NET, Ajax, Web Services and MS SQL Server Database. Uses ASP .NET authentication mechanism.Test Project (ignore): This is used to demonstrate CodePlex at meetings. Please ignore this project.Transform Config: Transfom Config lets you use the new configuration transformation feature in Visual Studio 2010 without performing a publish on a web application p...unsocialcity: trying to make a game for facebook called <projectname> - just seemed like a fun idea http://apps.facebook.com/unsocialcityVorbisPlayer: VorbisPlayer is the audio user control for Silverlight games. It plays loop-sets seamless, it solves the short sound problem, and it can play sound...New ReleasesA Guide to Parallel Programming: Drop 5 - Guide Preface, Chapters 1 - 7, and code: This is Drop 5 with Guide Preface, Chapters 1 - 7, Appendix B, Glossary, and References, and the accompanying code samples. This drop requires Visu...CC.Hearts Screen Saver: CC.Hearts Screen Saver 1.0.10.610: The third release of CC.Hearts Screen Saver. Key features are: Further performance enhancements Keyboard commands (Press ? for help) Help Popu...Fiddler Delayed Responses Extension: v1 beta: UI improvement . drag and drop . session markers . icons . layout Algorithm review . Performance issues Thanks to Eric Lawrence for his ideas.FontViewer 2010: FontViewer 2010 (Codename Eraser): This is the installer for the development version ("Eraser") of FontViewer 2010. Because many of the features are under development, functionality...Genuilder: Genuilder 1.2: First release of Genuilder.Extensibility.ImageResizer for Albulle: ImageResizer1.0-bin: Première version. Permet de déployer des images dans un système de fichier (local).imdb movie downloader: myImdb 0.9.5: myImdb 0.9.5KooBoo Image Gallery: Beta 4: This new version has a new example using s3slider script http://www.serie3.info/s3slider/demonstration.html thanks to mshimao Now there are two pl...LogikBug's IoC Container: LogikBug's IoC Container v1.1.1: In this release: I extended the Extensibility namespace. Fixed a few minor issues with the Extensibility namespace.LRS: jlrs: asdfaLRS: jlrs src: jlrs srcMiniTwitter: 1.14: MiniTwitter 1.14 更新内容 修正 リストのインポートをキャンセルしてもタイムラインの名前がリストの名前になるバグを修正 OAuth の承認を取り消した後、再ログインできないバグを修正 インポートするリストを選択せずにインポートをクリックすると落ちるバグを修正 追加 ...NETris - ASP .NET, AJAX, Web Service based Tetris Game: NETris - Source Code and Documentation: Fully functional prototype. Please note that documentation is written in the form of a report as the project was an assignment at Coventry University.Object/Relational Mapper & Code Generator in Net 2.0 for Relational & XML Schema: 2.10: Minor release, incremental changes to sample website and UI templates.Opalis Community Releases: Integration Pack for Standard OIS Logging: The Integration Pack for Standard OIS Logging provides extended Policy Logging functions to OIS and MSSQL. This Integration Pack adds the followin...PicassoCms: 0.6: More intuitive UI, new controlsPowerAuras: PowerAuras-3.0.0K-beta2: New Auras: Item Name Equipment Slot Tracking Changes from beta1 5 new aura textures Fixed Tracking bug Added graphical equipment slot sele...PowerPivot Sample Data: PowerPivot for Excel Tutorial Sample Data-v.2: The PowerPivot Tutorial Sample Data-Version 2 download includes a variety of data sources that you can use to complete the tutorial in the PowerPiv...Powwa: First build: Unpack & built with NetBean 6.8Quick Performance Monitor: Version 1.4: Added functionality to add and remove performance counters at run time. Also added saving and loading to file so sets of performance counters can b...Resonance: TrainNode Client Library: Libraries to access the TrainNode ServiceSharePoint 2010 Taxonomy Import Utility: TaxonomyBuilder Version 1.0.2: New Features Added support for additional term labels per term Added support for Term Set Owners Added support for Term Set stakeholders Upda...Silverlight for Umbraco Media Objects (SUMO): Community Tech Preview: The CTP for SUMO is now live, feedback appreciated!Silverlight Reporting: Initial Release: This is the first release of the code. It includes the source code from Pete's blog post article on Silverlight reporting.Simple.NET: Simple.Mocking 1.0.0.7: Initial version of a new mocking framework for .NET Revision 1: Expect.AnyInocationOn<T>(T target) changed to Expect.AnyInocationOn(object target...Smart Voice: Smart Voice 0.2.2: Changelog: Fixed more bugs Added a readme into the archiveSoulHackers Demon Unite(Chinese version): WPFClient pre alpha 2: pre alpha 2, need your feedbackSquiggle - A Free open source Lan Messenger: Squiggle 1.5: File Transfer capability added (With drag/drop support) Message text box maintains history of last 10 messages and you can retrieve them by CTRL+U...SSIS Expression Editor & Tester: Expression Editor and Tester v1.0.1.0: Minor updated release of expression editor tool and editor control. Download and extract the files to get started, no install required. Changes Si...StreamInsight Samples: GregLow HighwayMonitor Samples: Initial Upload of GregLow HighwayMonitor StreamInsight samples. These samples are used in the upcoming free eClinic for StreamInsight and have been...tChat - ASP.NET, Ajax & Web Service based Chat Room: tChat Source Code and Documentation: Functional prototype. T-SQL scripts can be found in the SQL folder. Please note that the documentation is written in a format of a report for a "du...Transform Config: Initial Release: This is the initial release of the project. It's all been thrown together quickly so it's lacking error handling etc, but it's still fully function...UrzaGatherer: UrzaGatherer v2.0.2: Integrate the support of SQL Server Compact Edition 3.5 SP2 for a better portability.Value Injecter: map anything to anything anyway you might imagine: ValueInjecter 1.9: Features map anything to anything flattening unflattening includes sample projects for: asp.net mvc asp.net web-forms win-formsVCC: Latest build, v2.1.30610.0: Automatic drop of latest buildVisual Studio DSite: Picture SlideShow Viewer (Visual C++ 2008): A picture slidershow viewer.VorbisPlayer: VorbisPlayer: The first release of the Silverlight VorbisPlayer, including source code and example files.WCF 4 Templates for Visual Studio 2010: AnonymousOverHttps Template: Produces a WCF service application configured for anonymous calls over HTTPS/SSL. Supplies a BasicHttpBinding default configured for Transport secu...Most Popular ProjectsHaoRan_TokyoTyrantClient.NET Transactional File ManagerSOLID by exampleMemetic NPC Behavior ToolkitSharpotify - Spotify .Net LibraryWCF 4 Templates for Visual Studio 2010SFTP Component for .NET CSharp, VB.NET, and ASP.NETUltimate FTP Component for .NET C#, VB.NET and ASP.NETAnurag Pallaprolu's Code RepositoryBigfootMVCMost Active ProjectsCommunity Forums NNTP bridgejQuery Library for SharePoint Web ServicesRhyduino - Arduino and Managed Codepatterns & practices – Enterprise LibraryNB_Store - Free DotNetNuke Ecommerce Catalog ModuleCassandraemonBlogEngine.NETMediaCoder.NETAndrew's XNA HelpersStyleCop

    Read the article

  • Data capture from other sheet into Summary sheet

    - by Hemant
    an Excel workbook which has Summary sheet, Pending and Master Sheet. My requirement is below and try to develop a Macro or VB logic for excel • I want to control this workbook from Summary sheet. o Generate Fault Summary – ? I have set logic but if doesn’t give warning if sheet name is exists , so need to add this logic . ? When we press the Fault Report Summary command button then it copy the master sheet with cell “A6” Name and will hide the Master sheet. Again when you select the another Month name then it will generate the sheet for that month name. o Generate Toll System Uptime ? When I select the sheet name and “Week” then Press the “Enter “Command button then it should get the result from that sheet number . Each sheet number has Month detail in B2 Cell. ? To calculate the Uptime formula for Week wise is • Week-01 = (1680-SUMIFS(L5:L23,B5:B23,"="&B2,B5:B23,"<="&(B2+6)))/1680 • Week-02 =(1680-SUMIFS(L5:L23,B5:B23,"="&(B2+7),B5:B23,"<="&(B2+13)))/1680 • Week-03 =(1680-SUMIFS(L5:L23,B5:B23,"="&(B2+14),B5:B23,"<="&(B2+20)))/1680 • Week-04 =(1680-SUMIFS(L5:L23,B5:B23,"="&(B2+21),B5:B23,"<="&(B2+27)))/1680 • Month =(1680-SUMIFS(L5:L23,B5:B23,"="&(B2),B5:B23,"<="&(DATE(YEAR(B2),1+MONTH(B2),1)-1)))/1680 ? Result should reflect in Summary sheet at B18 cell . o Pending Fault Report Summary ? When segregate the report on its status like which one is open or Close . It is open then it is Pending Fault Report and when it is Close status it means it is closed. ? If any fault which has OPEN status in all sheets(Jan-13,Feb-13,Mar-13….etc) then it should be come as well as in Pending Sheet which ascending date order. ? When it’s status is changed then it should be moved in that month sheet or nearby fault created date. It status is close then it should not be available in pending sheet as it’s status is Closed. ? Each fault has Reported date and we monitor all fault according reported date. ? When we press the Update Fault Report Summary command button then it should update as above logic. ? Some time we export the Pending fault report , so date calendar should be present in Start and End date to Choose the date. When we press the Export command line then it should export the Pending fault report and able to save in Excel,PDF.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >