working on it ...

Filters

Explore Public Snippets

Sort by

Found 231 snippets matching: in-memory

    public by cghersi  3309  1  8  1

    LINQ: How to retrieve an IEnumerable collection with simple query

    This is a simple query in Linq to retrieve the list of Users that have some specified condition (in this case Active == true). Please note the == operator in the where clause (and in general all C# operators apply). Linq is excellent in writing fast and effective in-memory query on lists, dictionaries, etc.
    ICollection<User> users = new List<User>();
    users.Add(new User("Tom"));
    users.Add(new User("Mark"));
    
    IEnumerable<User> result = (
    	from user in users 
    	where user.Active == true 
    	select user); 

    public by Geometry  1149  0  6  0

    ToText: Initializes a new instance of the <see cref="CsvWriter"/> class to write the CSV fields to a in-memory string.

    Initializes a new instance of the class to write the CSV fields to a in-memory string. A to write to.
    /// <summary>
    ///   Initializes a new instance of the <see cref="CsvWriter"/> 
    ///   class to write the CSV fields to a in-memory string.
    /// </summary>
    /// 
    /// <param name="builder">A <see cref="T:StringBuilder"/> to write to.</param>
    /// 
    public static CsvWriter ToText(StringBuilder builder)
    {
        return new CsvWriter(new StringWriter(builder));
    }

    public by Geometry  409  0  5  0

    Alloc: Allocate unmanaged memory.

    Allocate unmanaged memory. Memory size to allocate. Return's pointer to the allocated memory buffer. The method allocates requested amount of memory and returns pointer to it. It may avoid allocation in the case some caching scheme is uses and there is already enough allocated memory available. There is insufficient memory to satisfy the r
    private static List<CacheBlock> memoryBlocks = new List<CacheBlock>( );
    // busy blocks in cache
    private static int busyBlocks = 0;
    // maximum memory blocks to cache
    private static int maximumCacheSize = 3;
    // maximum block size to cache
    private static int maxSizeToCache = 20 * 1024 * 1024;
    // minimum block size to cache
    private static int minSizeToCache = 10 * 1024;
    // current cache size
    private static int currentCacheSize = 0;
    // amount of cached memory
    private static int cachedMemory = 0;
    
    /// <summary>
    /// Allocate unmanaged memory.
    /// </summary>
    /// 
    /// <param name="size">Memory size to allocate.</param>
    /// 
    /// <returns>Return's pointer to the allocated memory buffer.</returns>
    /// 
    /// <remarks>The method allocates requested amount of memory and returns pointer to it. It may avoid allocation
    /// in the case some caching scheme is uses and there is already enough allocated memory available.</remarks>
    /// 
    /// <exception cref="OutOfMemoryException">There is insufficient memory to satisfy the request.</exception>
    /// 
    public static IntPtr Alloc( int size )
    {
        lock ( memoryBlocks )
        {
            // allocate memory block without caching if cache is not available
            if ( ( busyBlocks >= maximumCacheSize ) || ( size > maxSizeToCache ) || ( size < minSizeToCache ) )
                return Marshal.AllocHGlobal( size );
    
            // if all cached blocks are busy, create new cache block
            if ( currentCacheSize == busyBlocks )
            {
                IntPtr memoryBlock = Marshal.AllocHGlobal( size );
                memoryBlocks.Add( new CacheBlock( memoryBlock, size ) );
    
                busyBlocks++;
                currentCacheSize++;
                cachedMemory += size;
    
                return memoryBlock;
            }
    
            // find free memory block with enough memory
            for ( int i = 0; i < currentCacheSize; i++ )
            {
                CacheBlock block = memoryBlocks[i];
    
                if ( ( block.Free == true ) && ( block.Size >= size ) )
                {
                    block.Free = false;
                    busyBlocks++;
                    return block.MemoryBlock;
                }
            }
    
            // finaly find first free memory block and resize it
            for ( int i = 0; i < currentCacheSize; i++ )
            {
                CacheBlock block = memoryBlocks[i];
    
                if ( block.Free == true )
                {
                    // remove this block cache
                    Marshal.FreeHGlobal( block.MemoryBlock );
                    memoryBlocks.RemoveAt( i );
                    currentCacheSize--;
                    cachedMemory -= block.Size;
    
                    // add new one
                    IntPtr memoryBlock = Marshal.AllocHGlobal( size );
                    memoryBlocks.Add( new CacheBlock( memoryBlock, size ) );
    
                    busyBlocks++;
                    currentCacheSize++;
                    cachedMemory += size;
    
                    return memoryBlock;
                }
            }
    
            return IntPtr.Zero;
        }
    }

    public by snip2code  3040  1  5  0

    Filtered COUNT (*) in Linq

    This is a very effective method to count in-memory a given collection (Users), with an established filter (active == true). Really fast, really simple, Linq style!!
    (from user in Users where user.Active == true select user).Count();

    public by msdn  1635  1  7  0

    Main: This is an extension of an in-memory provider sample that is used to illustrate the responsibilites of a provider working on behalf of a store. For instance, what do do with an item create/update/delete, how to get changes, how to app...

    This is an extension of an in-memory provider sample that is used to illustrate the responsibilites of a provider working on behalf of a store. For instance, what do do with an item create/update/delete, how to get changes, how to apply changes, how to detect conflicts, and how to resolve them using a custom action such as merge... Please
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Synchronization;
    
    public static MySimpleDataStore storeA;
    public static MySimpleDataStore storeB;
    public static MySimpleDataStore storeC;
    
    /// <summary>
    /// This is an extension of an in-memory provider sample that is used to illustrate the responsibilites of a provider working on behalf 
    /// of a store. For instance, what do do with an item create/update/delete, how to get changes, how to apply changes, how to detect conflicts, 
    /// and how to resolve them using a custom action such as merge...
    /// 
    /// Please note that this sample is most useful with breakpoints in MyTestProgram.cs to find out HOW synchronization using the 
    /// Microsoft Sync Framework works. This sample is not designed to be a boot-strapper like the NTFS providers for native and managed...
    /// </summary>
    /// <param name="args"></param>
    public static void Main(string[] args)
    {
        const string DATA = "data";
        string providerA = "A";
        string providerB = "B";
        string providerC = "C";
        List<string> arguments = new List<string>(args);
    
        //start clean
        CleanUpProvider(providerA);
        CleanUpProvider(providerB);
        CleanUpProvider(providerC);
    
        //Initialize the stores
        storeA = new MySimpleDataStore();
        storeB = new MySimpleDataStore();
        storeC = new MySimpleDataStore();
    
        //Create items on each store using a global ID and the data of the item (Note, in order to verify results against 
        //a baseline we are using hardcoded global ids for the items. In a real application CreateItem should be called without
        //the Guid parameter, which would generate a new Guid id and return it.
        Guid[] itemIds = new Guid[7];
        itemIds[1] = new Guid("11111111-1111-1111-1111-111111111111");
        itemIds[2] = new Guid("22222222-2222-2222-2222-222222222222");
        itemIds[3] = new Guid("33333333-3333-3333-3333-333333333333");
        itemIds[4] = new Guid("44444444-4444-4444-4444-444444444444");
        itemIds[5] = new Guid("55555555-5555-5555-5555-555555555555");
        itemIds[6] = new Guid("66666666-6666-6666-6666-666666666666");
    
        storeA.CreateItem(new ItemData(DATA, "1"), itemIds[1]);
        storeA.CreateItem(new ItemData(DATA, "2"), itemIds[2]);
        storeB.CreateItem(new ItemData(DATA, "3"), itemIds[3]);
        storeB.CreateItem(new ItemData(DATA, "4"), itemIds[4]);
        storeC.CreateItem(new ItemData(DATA, "5"), itemIds[5]);
        storeC.CreateItem(new ItemData(DATA, "6"), itemIds[6]);
    
        //Show the contents of the stores, prior to ANY any synchronization...
        Console.WriteLine("Show the contents of the stores, prior to any synchronization...");
        Console.WriteLine(new MySyncProvider(providerA, storeA).ToString());
        Console.WriteLine(storeA.ToString());
        Console.WriteLine(new MySyncProvider(providerB, storeB).ToString());
        Console.WriteLine(storeB.ToString());
        Console.WriteLine(new MySyncProvider(providerC, storeC).ToString());
        Console.WriteLine(storeC.ToString());
    
        //Sync providers A and provider B
        DoBidirectionalSync(providerA, storeA, providerB, storeB);
    
        //Create an update-update conflict on item 1 and show merge... (Note - this sample handles update-update conflicts and simply merges the data)
        Console.WriteLine("A and B are going to create a conflict on item 1. A writes 'Did Merging' and B writes 'Work?'");
    
        //Create an update-update conflict to merge...
        storeA.UpdateItem(itemIds[1], new ItemData(DATA, "Did Merging"));
        storeB.UpdateItem(itemIds[1], new ItemData(DATA, " Work?"));
    
        //Sync providers A and provider B
        DoBidirectionalSync(providerA, storeA, providerB, storeB);
    
        //Delete an item on B and show that the delete propagates
        Console.WriteLine("Deleting item '4' on B");
        storeB.DeleteItem(itemIds[4]);
    
        //Sync B and C
        DoBidirectionalSync(providerB, storeB, providerC, storeC);
    
        //Close the sync loop by syncing A and C
        Console.WriteLine("Closing the \"sync loop\" by syncing A and C...");
        DoBidirectionalSync(providerA, storeA, providerC, storeC);
    
        //Delete item 2 on B
        Console.WriteLine("{0}Deleting item '2' on B.", Environment.NewLine);
        storeB.DeleteItem(itemIds[2]);
    
        // Sync B and C
        DoBidirectionalSync(providerB, storeB, providerC, storeC);
    
        //Cleanup Tombstones on B
        Console.WriteLine("{0}Clean up Tombstones on B.", Environment.NewLine);
        new MySyncProvider(providerB, storeB).CleanupTombstones(TimeSpan.Zero);
    
        // Sync B and C
        DoBidirectionalSync(providerB, storeB, providerC, storeC);
    
        //Close the sync loop by syncing A and C
        DoBidirectionalSync(providerA, storeA, providerC, storeC);
    
        if (arguments.Contains("-q") != true)
        {
            Console.WriteLine("Sync has finished...");
            Console.ReadLine();
        }
    }

    public by msdn  1105  0  7  0

    Main: This class demonstrates how Microsoft Sync Framework simple providers are used to synchronize three in-memory item stores. The code creates data changes that are propagated, as well as conflicts that are detected and resolve...

    This class demonstrates how Microsoft Sync Framework simple providers are used to synchronize three in-memory item stores. The code creates data changes that are propagated, as well as conflicts that are detected and resolved. We recommend that you add breakpoints in this class to understand how synchronization works when using simple pr
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Synchronization;
    
    public static MySimpleDataStore storeA;
    public static MySimpleDataStore storeB;
    public static MySimpleDataStore storeC;
    
    /// <summary>
    /// This class demonstrates how Microsoft Sync Framework simple providers are used
    /// to synchronize three in-memory item stores. The code creates data changes that 
    /// are propagated, as well as conflicts that are detected and resolved.
    /// 
    /// We recommend that you add breakpoints in this class to understand how synchronization 
    /// works when using simple providers.
    /// </summary>
    public static void Main(string[] args)
    {
        const string DATA = "data";
        string providerA = "A";
        string providerB = "B";
        string providerC = "C";
        List<string> arguments = new List<string>(args);
    
        //Start clean.
        CleanupProvider(providerA);
        CleanupProvider(providerB);
        CleanupProvider(providerC);
    
        //Initialize the in-memory item stores.
        storeA = new MySimpleDataStore();
        storeB = new MySimpleDataStore();
        storeC = new MySimpleDataStore();
    
        //Create items in each store by using a global ID and the data for the item (a constant in this case).
        //Note: in order to verify results against a baseline, we use a hardcoded global 
        //ID for each item. In a real application the ID would typically be generated.
        storeA.CreateItem(new ItemData(DATA, "1111"), 1);
        storeA.CreateItem(new ItemData(DATA, "2222"), 2);
        storeB.CreateItem(new ItemData(DATA, "3333"), 3);
        storeB.CreateItem(new ItemData(DATA, "4444"), 4);
        storeC.CreateItem(new ItemData(DATA, "5555"), 5);
        storeC.CreateItem(new ItemData(DATA, "6666"), 6);
    
        //Show the contents of the stores, prior to any synchronization sessions.
        Console.WriteLine("Show the contents of the stores, prior to any synchronization...");
        Console.WriteLine(new MyFullEnumerationSimpleSyncProvider(providerA, storeA).ToString());
        Console.WriteLine(storeA.ToString());
        Console.WriteLine(new MyFullEnumerationSimpleSyncProvider(providerB, storeB).ToString());
        Console.WriteLine(storeB.ToString());
        Console.WriteLine(new MyFullEnumerationSimpleSyncProvider(providerC, storeC).ToString());
        Console.WriteLine(storeC.ToString());
    
        //Synchronize provider A and provider B.
        DoBidirectionalSync(providerA, storeA, providerB, storeB);
    
        //Create an update-update conflict on item 1 and resolve the conflict by merging
        //the data from the two item stores. Note: this sample demonstrates only update-update conflicts.
        Console.WriteLine("A and B are going to create a conflict on item 1. A writes 'Did Merging' and B writes 'Work?'");
    
        //Create an update-update conflict to merge.
        storeA.UpdateItem(1, new ItemData(DATA, "Did Merging"));
        storeB.UpdateItem(1, new ItemData(DATA, " Work?"));
    
        //Synchronize provider A and provider B.
        DoBidirectionalSync(providerA, storeA, providerB, storeB);
    
        //Create a create-create constraint conflict to merge.
        storeA.CreateItem(new ItemData(DATA, "Did Merging"), 7);
        storeB.CreateItem(new ItemData(DATA, " Work again?"), 7);
    
        //Sync provider A and provider B.
        DoBidirectionalSync(providerA, storeA, providerB, storeB);
    
        //Delete an item from store B and show that the delete propagates.
        Console.WriteLine("Deleting item '4' on B");
        storeB.DeleteItem(4);
    
        //Synchronize provider B and provider C.
        DoBidirectionalSync(providerB, storeB, providerC, storeC);
    
        //Close the loop by synchronizing provider A and provider C.
        Console.WriteLine("Closing the \"sync loop\" by syncing A and C...");
        DoBidirectionalSync(providerA, storeA, providerC, storeC);
    
        //Delete item 2 from store B.
        Console.WriteLine("{0}Deleting item '2' on B.", Environment.NewLine);
        storeB.DeleteItem(2);
    
        //Synchronize provider B and provider C.
        DoBidirectionalSync(providerB, storeB, providerC, storeC);
    
        //Clean up all deleted items from metadata store B.
        Console.WriteLine("{0}Clean up deleted items on B.", Environment.NewLine);
        new MyFullEnumerationSimpleSyncProvider(providerB, storeB).CleanupDeletedItems(TimeSpan.Zero);
    
        //Synchronize provider B and provider C.
        DoBidirectionalSync(providerB, storeB, providerC, storeC);
    
        //Close the sync loop by syncing provider A and provider C.
        DoBidirectionalSync(providerA, storeA, providerC, storeC);
    
        if (arguments.Contains("-q") != true)
        {
            Console.WriteLine("Sync has finished...");
            Console.ReadLine();
        }
    }

    public by msdn  1612  1  7  0

    DateName

    // Signature stolen from System.Data.Entity.SqlServer.SqlFunctions, // which cannot be used for mapping in-memory objects :-(
    using System;
    using System.Data.Entity;
    
    // Signature stolen from System.Data.Entity.SqlServer.SqlFunctions, 
    // which cannot be used for mapping in-memory objects :-(
    [DbFunction("SqlServer", "DATENAME")]
    public static string DateName(string datePartArg, DateTimeOffset date)
    {
        if (datePartArg == "month")
        {
            return date.ToString("MMMM");
        }
    
        throw new ArgumentOutOfRangeException("datePartArg", "Value '" + datePartArg + "' is not supported");
    }

    public by msdn  1670  0  7  0

    DatePart

    // Signature stolen from System.Data.Entity.SqlServer.SqlFunctions, // which cannot be used for mapping in-memory objects :-(
    using System;
    using System.Data.Entity;
    
    // Signature stolen from System.Data.Entity.SqlServer.SqlFunctions, 
    // which cannot be used for mapping in-memory objects :-(
    [DbFunction("SqlServer", "DATEPART")]
    public static int? DatePart(string datePartArg, DateTimeOffset date)
    {
        if (datePartArg == "year")
        {
            return date.Year;
        }
    
        throw new ArgumentOutOfRangeException("datePartArg", "Value '" + datePartArg + "' is not supported");
    }

    public by msdn  1493  0  7  0

    ReadChildElements: This method deserializes all child model elements.

    This method deserializes all child model elements. The caller will position the reader at the open tag of the first child XML element to deserialized. This method will read as many child elements as it can. It returns under three circumstances: 1) When an unknown child XML element is encountered. In this case, this method will position the
    using DslModeling = global::Microsoft.VisualStudio.Modeling;
    using DslDiagrams = global::Microsoft.VisualStudio.Modeling.Diagrams;
    
    /// <summary>
    /// This method deserializes all child model elements.
    /// </summary>
    /// <remarks>
    /// The caller will position the reader at the open tag of the first child XML element to deserialized.
    /// This method will read as many child elements as it can. It returns under three circumstances:
    /// 1) When an unknown child XML element is encountered. In this case, this method will position the reader at the 
    ///    open tag of the unknown element. This implies that if the first child XML element is unknown, this method 
    ///    should return immediately and do nothing.
    /// 2) When all child XML elemnets are read. In this case, the reader will be positioned at the end tag of the parent element.
    /// 3) EOF.
    /// </remarks>
    /// <param name="serializationContext">Serialization context.</param>
    /// <param name="reader">XmlReader to read serialized data from.</param>
    /// <param name="element">In-memory Comment instance that will get the deserialized data.</param>
    private static void ReadChildElements(DslModeling::SerializationContext serializationContext, Comment element, global::System.Xml.XmlReader reader)
    {
    	if (!serializationContext.Result.Failed && !reader.EOF && reader.NodeType == global::System.Xml.XmlNodeType.Element)
    	{
    		if (string.Compare(reader.LocalName, "annotatedElement", global::System.StringComparison.CurrentCulture) == 0)
    		{
    			if (reader.IsEmptyElement)
    			{	// No instance of this relationship, just skip
    				DslModeling::SerializationUtilities.Skip(reader);
    			}
    			else
    			{
    				DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <annotatedElement>
    				ReadCommentsAnnotateElementInstances(serializationContext, element, reader);
    				DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </annotatedElement>
    			}
    		}
    	}
    }

    public by msdn  1374  0  6  0

    ReadChildElements: This method deserializes all child model elements.

    This method deserializes all child model elements. The caller will position the reader at the open tag of the first child XML element to deserialized. This method will read as many child elements as it can. It returns under three circumstances: 1) When an unknown child XML element is encountered. In this case, this method will position the
    using DslModeling = global::Microsoft.VisualStudio.Modeling;
    using DslDiagrams = global::Microsoft.VisualStudio.Modeling.Diagrams;
    
    /// <summary>
    /// This method deserializes all child model elements.
    /// </summary>
    /// <remarks>
    /// The caller will position the reader at the open tag of the first child XML element to deserialized.
    /// This method will read as many child elements as it can. It returns under three circumstances:
    /// 1) When an unknown child XML element is encountered. In this case, this method will position the reader at the 
    ///    open tag of the unknown element. This implies that if the first child XML element is unknown, this method 
    ///    should return immediately and do nothing.
    /// 2) When all child XML elemnets are read. In this case, the reader will be positioned at the end tag of the parent element.
    /// 3) EOF.
    /// </remarks>
    /// <param name="serializationContext">Serialization context.</param>
    /// <param name="reader">XmlReader to read serialized data from.</param>
    /// <param name="element">In-memory Constraint instance that will get the deserialized data.</param>
    private static void ReadChildElements(DslModeling::SerializationContext serializationContext, Constraint element, global::System.Xml.XmlReader reader)
    {
    	if (!serializationContext.Result.Failed && !reader.EOF && reader.NodeType == global::System.Xml.XmlNodeType.Element)
    	{
    		if (string.Compare(reader.LocalName, "specification", global::System.StringComparison.CurrentCulture) == 0)
    		{
    			if (reader.IsEmptyElement)
    			{	// No instance of this relationship, just skip
    				DslModeling::SerializationUtilities.Skip(reader);
    			}
    			else
    			{
    				DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <specification>
    				ReadConstraintHasSpecificationInstance(serializationContext, element, reader);
    				DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </specification>
    			}
    		}
    	}
    }
    • Public Snippets
    • Channels Snippets