Profile

Cover photo
Cycoder's Coding Cafe`
13 followers|1,971 views
AboutPostsPhotosVideos

Stream

 
C#:

Convert a data row to an object (auto-populate properties named same as result set columns) using reflection

        #region ConvertDataToObject
        /// <summary>
        /// Transform Data from a DataRow to an Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pDataRow"></param>
        /// <returns></returns>
        public static T ConvertDataToObject<T>(DataRow pDataRow) where T : new()
        {
            T pObject = new T();
            foreach (PropertyInfo property in pObject.GetType().GetProperties())
            {
                if (pDataRow.Table.Columns.IndexOf(property.Name) > -1)
                {
                    if (pDataRow[property.Name] != DBNull.Value)
                    {
                        Type convertType = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)) ? Nullable.GetUnderlyingType(property.PropertyType) : property.PropertyType;
                        if (convertType.IsEnum)
                        {
                            if (pDataRow[property.Name].ToString() != String.Empty)
                            {
                                property.SetValue(pObject, Enum.Parse(convertType, pDataRow[property.Name].ToString(), true), null);
                            }
                        }
                        else
                        {
                            property.SetValue(pObject, Convert.ChangeType(pDataRow[property.Name], convertType), null);
                        }
                    }
                }
            }
            return pObject;
        }
        #endregion ConvertDataToObject
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
iOS Objective C, SDK 5+, iOS 5+:

Easy way to hide the "More" tab's nav bar when an item on the more list selected, and ensure the list is visible again on next navigate to More.

Subclass your UITabBarController and make it a UINavigationControllerDelegate.

@interface MainTabBarController : UITabBarController<UINavigationControllerDelegate>

Set the more controller delegate in ViewDidLoad:

    //Set more delegate handler
    [self.moreNavigationController setDelegate:self];

Then drop the code below in the proper delegate methods for the TabBar Controller and More Controller:

#pragma mark - UITabbarDelegate
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    //More has no title
    //So if we have a title (this is more page) and teh more page view isn't the
    //more list, set it to the more list so when we nav back, it's at the list since we hide the nav bar.
    if(item.title && (self.moreNavigationController.visibleViewController != [self.moreNavigationController.viewControllers objectAtIndex:0]))
    {
        //Reset to more list view
        [self.moreNavigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UINavigationControllerDelegate
// Called when the navigation controller shows a new top view controller via a push, pop or setting of the view controller stack.
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    UIViewController *moreListView = [self.moreNavigationController.viewControllers objectAtIndex:0];
    BOOL hideNavBar = (self.moreNavigationController.visibleViewController != moreListView);
    [self.moreNavigationController setNavigationBarHidden:hideNavBar];
}
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
MS SQL Server/TSQL

SQL Tech Note: SQL XML (OpenXML vs. Nodes)
------------------------------------------------------------------------

There are 2 typical methods to work with XML Data in SQL.

OpenXML
• Requires error handling to ensure paired usage of sp_xml_preparedocument and sp_xml_removedocument
• Limits maximum memory usage for XML parsing of an instance to 1/8th of allocated SQL memory
• Performs better in many cases than “Nodes” method on low end CPUs
• Pattern to be used:

      SET NOCOUNT ON

      DECLARE @ErrorMessage NVARCHAR(4000)
      DECLARE @ErrorSeverity INT
      DECLARE @ErrorState INT
      DECLARE @Error INT

      DECLARE @idoc INT  
 
      --Create an internal representation of the XML document.  
      BEGIN TRY
            EXEC sp_xml_preparedocument @idoc OUTPUT,@XmlDoc          
 
            --Do stuff
            SELECT      APInvoiceHeaderID
            FROM  OPENXML (@idoc,'/APInvoiceHeaders/APInvoiceHeader', 1)  
                  WITH   
                  (  
                        APInvoiceHeaderID  VARCHAR(36)  '@APInvoiceHeaderID' 
                  )
      END TRY
      BEGIN CATCH
            SELECT 
                 @ErrorMessage= ERROR_MESSAGE(),
                 @ErrorSeverity= ERROR_SEVERITY(),
                 @ErrorState= ERROR_STATE(),
                 @Error=@@ERROR
      END CATCH
      
      --Finally 
      BEGIN TRY
            EXEC sp_xml_removedocument @idoc
      END TRY
      BEGIN CATCH
      END CATCH
      
      -- Use RAISERROR to return error
      -- information about the original error that caused
      -- execution to jump to the CATCH block.
      IF(@Error<> 0)
      BEGIN
            RAISERROR (@ErrorMessage,-- Message text.
                           @ErrorSeverity,-- Severity.
                           @ErrorState-- State.
                           )
      END   


Nodes
• No known limit on maximum usage of allocated SQL memory; dynamically allocated
• Performs better in many cases than “OpenXML” method on high end CPUs
• Usage Sample:

SELECT TOP 1 T.InvoiceHeader.value('@APInvoiceHeaderID[1]','UNIQUEIDENTIFIER')
      FROM  @XmlDoc.nodes('/APInvoiceHeaders/APInvoiceHeader') T(InvoiceHeader)
      WHERE T.InvoiceHeader.value('@APInvoiceHeaderID[1]','UNIQUEIDENTIFIER') = APIR.APInvoiceHeaderID

Based on these findings, the implementation rules are as follows:
• If the XML is potentially unlimited in size or larger than 128MB, use OpenXML. This will protect overall SQL instance performance.
• If the XML is of a limited known size of 128MB or less, use the Nodes method.
• If the XML is larger than 2GB (the limit of the XML data type,)  use a CLR (C#) Stored Procedure
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
C#, .Net

Here is a tidy little function to make sure a file name is valid and safe. Note that this routine will remove path elements such as \\

        /// <summary>
        /// Make a filename string a safe name
        /// </summary>
        /// <param name="pFileName"></param>
        /// <returns></returns>
        static string SafeFileName(string pFileName)
        {
            string fileName = pFileName;
            foreach (char invalidChar in System.IO.Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(invalidChar.ToString(), String.Empty);
            }
            return fileName;
        }
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
iOS Objective C, SDK 5+:

In iOS SDK 5 and up, UISegmentedControlStyleBezeled has been deprecated for the UISegmentedControl.

Consider setting the type to Bordered in the xib/nib, and using the following code to resolve the issue while maintaining a consistent look in older iOS versions.

    //Setup segment types
    BOOL isIOS5orBetter = [[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0;
    
    NSDictionary *segmentTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:14],@"Font", nil];
    
    if(isIOS5orBetter)
    {
        [self.segmentControl setTitleTextAttributes:segmentTextAttributes forState:UIControlStateNormal];
    }
    else
    {
        [self.segmentControl setSegmentedControlStyle:UISegmentedControlStyleBezeled];
    }
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
iOS Objective C, SDK 4+:

Add the skip backup attribute to files that don't need backing up to avoid rejection due to Apple's iCloud Storage guidelines

#import <sys/xattr.h>

/*
 * Set skip iCloud backup attrib for file
 */
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL*)fileURL
{
    const char* filePath = [[fileURL path] fileSystemRepresentation];
    const char* attrName = "com.apple.MobileBackup";
    if (&NSURLIsExcludedFromBackupKey == nil) 
    {
        // iOS 5.0.1 and lower
        u_int8_t attrValue = 1;
        int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
        return result == 0;
    } 
    else 
    {
        // First try and remove the extended attribute if it is present
        int result = getxattr(filePath, attrName, NULL, sizeof(u_int8_t), 0, 0);
        if (result != -1) {
            // The attribute exists, we need to remove it
            int removeResult = removexattr(filePath, attrName, 0);
            if (removeResult == 0) 
            {
                NSLog(@"Removed extended attribute on file %@", fileURL);
            }
        }
        
        // Set the new key
        return [fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
Jordan Mechner's Prince of Persia Apple ][ 6502 ASM Source Code
1
David Bressler's profile photo
 
Looking through this brought back memories of some good times
Add a comment...
Have them in circles
13 people

Cycoder's Coding Cafe`

Shared publicly  - 
 
iOS Objective C, SDK 5+, iOS 5+:

Avoid a crash during in-app email, and direct a user to automated email account setup if needed.

if(![MFMailComposeViewController canSendMail])
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:support@apple.com"]];
}
else
{
    //Create and check for nil controller from the framework
    MFMailComposeViewController *mcvc = [[MFMailComposeViewController alloc] init];
    if(mcvc)
    {
        //Do mail stuff here
    }
}
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
C#, .Net

Nice little function to compress an existing file without eating a ton of memory. The buffer size is configurable:

        /// <summary>
        /// Compress a file
        /// </summary>
        /// <param name="pSourceFileName"></param>
        /// <param name="pKeepSourceFile"></param>
        /// <returns>Compressed FileName</returns>
        static string CompressFile(string pSourceFileName, int pBufferSize, bool pKeepSourceFile)
        {
            string compressedFileName = System.Guid.NewGuid().ToString();

            //Do it in chunks/stream to be memory conservative
            using (FileStream sourceFileStream = new FileStream(pSourceFileName, FileMode.Open, FileAccess.Read))
            {

                using (FileStream compressedFileStream = new FileStream(compressedFileName, FileMode.Create))
                {

                    using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                    {

                        using (BinaryWriter tempFileWriter = new BinaryWriter(compressionStream))
                        {
                            //Setup buffer
                            byte[] buffer = new byte[pBufferSize];
                            int bufferOffset = 0;
                            int bufferReadSize = 0;

                            //Read bytes into buffer[] and retain the number of bytes returned.
                            bufferReadSize = sourceFileStream.Read(buffer, 0, pBufferSize);

                            //Read all data that fits in our exact buffer size
                            while (bufferReadSize == pBufferSize)
                            {

                                //Write out
                                tempFileWriter.Write(buffer);

                                //update offset
                                bufferOffset += bufferReadSize;

                                //Next read
                                bufferReadSize = sourceFileStream.Read(buffer, 0, pBufferSize);
                            }

                            //Write out the remaining buffer
                            //tempFileWriter.Write(buffer, 0, (int)bufferReadSize);
                            Array.Resize<byte>(ref buffer, bufferReadSize);
                            tempFileWriter.Write(buffer);

                        }//using (BinaryWriter tempFileWriter

                    }//using (GZipStream compressionStream

                }//using (FileStream tempFileStream

            }//using (FileStream sourceFileStream

            //Cleanup source
            if (!pKeepSourceFile && System.IO.File.Exists(pSourceFileName))
            {
                System.IO.File.Delete(pSourceFileName);
            }

            //Return compressed file name
            return compressedFileName;
        }
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
iOS Objective C, SDK 4+, iOS 4+:

http://tinyurl.com/chh8xel
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
iOS Objective C, SDK 5+, iOS 5+:

Background thread that updates the UI once complete.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    //background thread code goes here


    dispatch_async(dispatch_get_main_queue(), 
    ^{
        //UI update code in here

    });

});
1
Add a comment...

Cycoder's Coding Cafe`

Shared publicly  - 
 
iOS Objective C:

Tip

In the latest versions of the SDK, you may get the error that a Window is expected to have a Root View Controller once application launch is complete.

One of many reasons you may get this message is if the Window is associated as a View Outlet for a view controller. Only the Root View Controller should be set.
1
Add a comment...
People
Have them in circles
13 people
Contact Information
Contact info
Email
Story
Tagline
Snippets, News and Samples for the SQL, C#, and iOS Objective C Developer
Introduction
Snippets, News and Samples for the SQL, C#, and iOS Objective C Developer