working on it ...

Filters

Explore Public Snippets

Sort by

Found 851 snippets matching: preserve

    public by micurs  6866149  356  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by cghersi  185245  1  6  1

    Use the Raw HTML content in XSLT transformations

    Usage of copy-of element allows to get the exact content of an XML node and put it as raw HTML, so that e.g. are not stripped out as instead happens with
    <myXmlNode>
    	<question>
    	Some text <br/> separated < br/> by new lines
    	</question>
    </myXmlNode>
    
    <span>
    	<xsl:copy-of select="question"/>
    </span>

    public by cghersi  3171  1  6  0

    Create a usage pattern for several heterogeneous methods

    Let's say we have several methods implemented in the same way but that should invoke different operations inside their implementation. e.g. we have a wrapper of API, and each API should be checked for the reload of endpoint if failed... Under these circumstances, C# lambda expressions should be very useful, but what about Java? Here there is a so
    public interface CallableOp<T> {
    	T exec();
    }
    
    /**
     * This is the generic method that provides the common implementation for several methods,
     * which are implemented in exec() method of the given input
     * @param op object of anonymous class that implement the internal logic of the method
     * @param clazz class of the returning object
     */
    public <T> T execOp(CallableOp<T> op, Class<T> clazz) {
    	try{
    		return op.exec();
    	}catch(WebServiceException webSerExc){
    		if (checkReloadEndpoint(webSerExc)) {
    			//with this exception we prepare reload endpoints and try again invoking ws
    			forcedReloaded = true;
    			return op.exec();
    		}else{
    			//forward the exception
    			throw webSerExc;
    		}
    	}
    }
    
    public void test() {
    	//here you don't need any cast nor reflection!
    	boolean res = execOp(new CallableOp<Boolean>() {
    		public Boolean exec() {
    			//parameters and other business logic may be implemented here 
    			//or directly in the test() method
    			int param1 = 1;
    			String param2 = "test";
    			return apiInvocation(param1, param2); // thi is the API invocation method 
    		}
    	}, Boolean.class);
    }

    public by cghersi @ PLAT.ONE  2378  6  6  1

    Add / remove visibility of some devices to a user in PLAT.ONE

    These two methods add and remove the visibility of a particular device for the given user. The data of the device are preserved in any case.
    public boolean associateDevice(int deviceID, int userID) throws Exception {
    	// 1. check that the user is already assigned a visibility at node level:
    	IPlatoneAPI api = getAPI();
    	IProxyPlatUser user = api.DB_GetPlatUser(userID);
    	if (user == null)
    		return false;
    	if (!user.isNodeLevelSecPolicy(APP_GARDEN_ID))
    		api.DB_ModifyPlatUserSecPolicy(APP_GARDEN_ID, userID, false, true);
    	
    	// 2. associate the device:
    	ArrayList<Integer> nodes = new ArrayList<Integer>();
    	nodes.add(deviceID);
    	return api.DB_AddAvailNodes4User(APP_GARDEN_ID, userID, nodes);
    }
    
    public boolean archiveDevice(int deviceID, int userID) throws Exception {
    	// 1. check that the user is already assigned a visibility at node level:
    	IPlatoneAPI api = getAPI();
    	IProxyPlatUser user = api.DB_GetPlatUser(userID);
    	if (user == null)
    		return false;
    	if (!user.isNodeLevelSecPolicy(APP_GARDEN_ID))
    		api.DB_ModifyPlatUserSecPolicy(APP_GARDEN_ID, userID, false, true);
    	
    	// 2. archive the device:
    	ArrayList<Integer> nodes = new ArrayList<Integer>();
    	nodes.add(deviceID);
    	api.DB_DeleteAvailNodes4User(APP_GARDEN_ID, userID, nodes);
    	
    	return true;
    }

    public by libby  1785  1  5  -1

    Remove commits, but keep local changes.

    Removes the last commit, but will preserve the local changes.
    Git
    git reset HEAD~1

    public by msdn  1543  0  6  0

    SaveAsync: Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances registered with <see cref="RegisterFrame"/> will also preserve their current navigation stack, which in turn gives their active <see cref="Pag...

    Save the current . Any instances registered with will also preserve their current navigation stack, which in turn gives their active an opportunity to save its state. An asynchronous task that reflects when session state has been saved.
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.ApplicationModel;
    using Windows.Storage;
    using Windows.Storage.Streams;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    
    private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
    private static List<Type> _knownTypes = new List<Type>();
    private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
    private const string sessionStateFilename = "_sessionState.xml";
    
    /// <summary>
    /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
    /// registered with <see cref="RegisterFrame"/> will also preserve their current
    /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
    /// to save its state.
    /// </summary>
    /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
    public static async Task SaveAsync()
    {
        try
        {
            // Save the navigation state for all registered frames
            foreach (var weakFrameReference in _registeredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }
    
            // Serialize the session state synchronously to avoid asynchronous access to shared
            // state
            MemoryStream sessionData = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, _sessionState);
    
            // Get an output stream for the SessionState file and write the state asynchronously
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
            using (Stream fileStream = await file.OpenStreamForWriteAsync())
            {
                sessionData.Seek(0, SeekOrigin.Begin);
                await sessionData.CopyToAsync(fileStream);
                await fileStream.FlushAsync();
            }
        }
        catch (Exception e)
        {
            throw new SuspensionManagerException(e);
        }
    }

    public by msdn  1258  0  7  0

    SaveAsync: Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances registered with <see cref="RegisterFrame"/> will also preserve their current navigation stack, which in turn gives their active <see cref="P...

    Save the current . Any instances registered with will also preserve their current navigation stack, which in turn gives their active an opportunity to save its state. An asynchronous task that reflects when session state has been saved.
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.ApplicationModel;
    using Windows.Storage;
    using Windows.Storage.Streams;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    
    private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
    private static List<Type> _knownTypes = new List<Type>();
    private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
    private const string sessionStateFilename = "_sessionState.xml";
    
    /// <summary>
    /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
    /// registered with <see cref="RegisterFrame"/> will also preserve their current
    /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
    /// to save its state.
    /// </summary>
    /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
    public static async Task SaveAsync()
    {
        try
        {
            // Save the navigation state for all registered frames
            foreach (var weakFrameReference in _registeredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }
    
            // Serialize the session state synchronously to avoid asynchronous access to shared
            // state
            MemoryStream sessionData = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, _sessionState);
    
            // Get an output stream for the SessionState file and write the state asynchronously
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
            using (Stream fileStream = await file.OpenStreamForWriteAsync())
            {
                sessionData.Seek(0, SeekOrigin.Begin);
                await sessionData.CopyToAsync(fileStream);
            }
        }
        catch (Exception e)
        {
            throw new SuspensionManagerException(e);
        }
    }

    public by msdn  1249  0  6  0

    SaveAsync: Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances registered with <see cref="RegisterFrame"/> will also preserve their current navigation stack, which in turn gives their active <see cref="Page"/> a...

    Save the current . Any instances registered with will also preserve their current navigation stack, which in turn gives their active an opportunity to save its state. An asynchronous task that reflects when session state has been saved.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using Windows.Storage.Streams;
    using System.Runtime.Serialization;
    using System.IO;
    using Windows.ApplicationModel;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    
    private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
    private static List<Type> _knownTypes = new List<Type>();
    private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
    private const string sessionStateFilename = "_sessionState.xml";
    
    /// <summary>
    /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
    /// registered with <see cref="RegisterFrame"/> will also preserve their current
    /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
    /// to save its state.
    /// </summary>
    /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
    public static async Task SaveAsync()
    {
        try
        {
            // Save the navigation state for all registered frames
            foreach (var weakFrameReference in _registeredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }
    
            // Serialize the session state synchronously to avoid asynchronous access to shared
            // state
            MemoryStream sessionData = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, _sessionState);
            
            // Get an output stream for the SessionState file and write the state asynchronously
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
            using (Stream fileStream = await file.OpenStreamForWriteAsync())
            {
                sessionData.Seek(0, SeekOrigin.Begin);
                await sessionData.CopyToAsync(fileStream);
            }
        }
        catch (Exception e)
        {
            throw new SuspensionManagerException(e);
        }
    }

    public by msdn  1085  0  6  0

    Main: By default serialization preserves all public properties of an object. This sample looks at an existing .NET class and shows how to make sure that information from instance of this class is preserved across serializ...

    By default serialization preserves all public properties of an object. This sample looks at an existing .NET class and shows how to make sure that information from instance of this class is preserved across serialization/deserialization when the information is not available in public properties of the class
    using System;
    using System.IO;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    
    /// <summary>
    /// By default serialization preserves all public properties of an object.
    ///
    /// This sample looks at an existing .NET class and shows how to make sure that
    /// information from instance of this class is preserved across serialization/deserialization
    /// when the information is not available in public properties of the class
    /// </summary>
    static void Main()
    {
        string typesPs1XmlPath = Path.Combine(Environment.CurrentDirectory, "Serialization02.types.ps1xml");
        if (!File.Exists(typesPs1XmlPath))
        {
            Console.WriteLine("Building the project in Visual Studio should have created a types.ps1xml file at the following path:");
            Console.WriteLine("{0}", typesPs1XmlPath);
            Console.WriteLine();
            Console.WriteLine("Cannot continue without this file being present.");
            return;
        }
    
        // Create a default InitialSessionState 
        InitialSessionState iss = InitialSessionState.CreateDefault();
        // Add our types.ps1xml file to the InitialSessionState
        // (one alternative would be to associate the file with a module or with a snap-in)
        iss.Types.Add(new SessionStateTypeEntry(typesPs1XmlPath));
    
        //
        // Demonstrate the effects of the types.ps1xml and DeserializingTypeConverter
        //
    
        using (Runspace myRunspace = RunspaceFactory.CreateRunspace(iss))
        {
            myRunspace.Open();
    
            //
            // Demonstrate that the deserializing an exception results in a live object
            //
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = myRunspace;
                powershell.AddScript(@"
                    # Get an System.Drawing.Point object
                    Add-Type -AssemblyName System.Drawing
                    $point = New-Object System.Drawing.Point 12,34
                            
                    # Verify that the extra property is hidden by default
                    Write-Output 'Below are the results of running $point | Format-List *   :'
                    $point | Format-List * | Out-String
                    Write-Output '----------------------------------------'
    
                    # Serialize the object
                    $point | Export-CliXml .\Serialization02.xml
    
                    # Deserialize the object
                    $deserializedPoint = Import-CliXml .\Serialization02.xml
    
                    # Verify that the extra property got serialized
                    Write-Output 'Below are the results of running $deserializedPoint | Get-Member   :'
                    $deserializedPoint | Get-Member | Out-String
                    Write-Output '----------------------------------------'
                    ");
                foreach (string s in powershell.Invoke<string>())
                {
                    System.Console.WriteLine(s);
                }
            }
    
            // Close the runspace and release any resources.
            myRunspace.Close();
        }
    
        System.Console.WriteLine("Hit any key to exit...");
        System.Console.ReadKey();
    }

    public by msdn  1092  0  6  0

    Main: This sample looks at an existing .NET class and shows how to make sure that information from selected public properties of this class is preserved across serialization/deserialization.

    This sample looks at an existing .NET class and shows how to make sure that information from selected public properties of this class is preserved across serialization/deserialization.
    /// <summary>
    /// This sample looks at an existing .NET class and shows how to make sure that
    /// information from selected public properties of this class is preserved across
    /// serialization/deserialization.
    /// </summary>
    private static void Main()
    {
        string typesPs1XmlPath = Path.Combine(Environment.CurrentDirectory, "Serialization01.types.ps1xml");
        if (!File.Exists(typesPs1XmlPath))
        {
            Console.WriteLine("Building the project in Visual Studio should have created a types.ps1xml file at the following path:");
            Console.WriteLine("{0}", typesPs1XmlPath);
            Console.WriteLine();
            Console.WriteLine("Cannot continue without this file being present.");
            return;
        }
    
        // Demonstrate the effects of the types.ps1xml and DeserializingTypeConverter
        using (Runspace myRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()))
        {
            myRunspace.Open();
    
            // Demonstrate that the deserializing an exception results in a live object
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = myRunspace;
                powershell.AddScript(@"
                    # Get an System.Drawing.Rectangle object
                    Add-Type -AssemblyName System.Drawing
                    $rectangle = New-Object System.Drawing.Rectangle 1,2,3,4
                            
                    # Without extra type.ps1xml Rectangle.Location property might get serialized as a string
                    Write-Output 'Below are serialization results without the extra types.ps1xml declarations: '
                    Export-CliXml -Input $rectangle -Depth 1 -Path Serialization01.xml
                    $deserializedRectangle = Import-CliXml Serialization01.xml
                    Write-Output ('$deserializedRectangle.Location is a ' + $deserializedRectangle.Location.PSTypeNames[0])
                    Write-Output '----------------------------------------'
    
                    # Update the system with the extra types.ps1xml declarations
                    Update-TypeData .\Serialization01.types.ps1xml
    
                    # After adding extra types.ps1xml declarations 
                    # chosen properties of Rectangle.Location will always get serialized
                    Write-Output 'Below are serialization results after adding the extra types.ps1xml declarations: '
                    Export-CliXml -Input $rectangle -Depth 1 -Path Serialization01.xml
                    $deserializedRectangle = Import-CliXml Serialization01.xml
                    Write-Output ('$deserializedRectangle.Location is a ' + $deserializedRectangle.Location.PSTypeNames[0])
                    if ($deserializedRectangle.Location.IsEmpty -eq $null)
                    {
                        Write-Output '$deserializedRectangle.Location.IsEmpty didnt get serialized'
                    }
                    Write-Output '----------------------------------------'
    
                    ");
                foreach (string s in powershell.Invoke<string>())
                {
                    System.Console.WriteLine(s);
                }
            }
    
            // Close the runspace and release any resources.
            myRunspace.Close();
        }
    
        System.Console.WriteLine("Hit any key to exit...");
        System.Console.ReadKey();
    }
    • Public Snippets
    • Channels Snippets