Dailycode.info

Short solution for short problems

Grabbing the image from AXIS (P1346) Network Camera

Thanks to the wonderful API this camera has, you do not need DLL's or Active X controls. You can just get an image for example by the API.

Here an example to get the image from the camera using c# (this can be used in a service, web service or other applications):

Uri test = new Uri("http://192.0.0.100/jpg/image.jpg");

WebClient wc = new WebClient();

wc.Credentials = new NetworkCredential("MyUser", "MyPassW0rd");

wc.DownloadFile(test, @"C:\TakePicture\picFromWS.jpg");

wc.Dispose(); 

 

 


iOS: Using multiple storyboards within a navigation controller.

I had a big story board file and I wanted to start to split it up in multiple storyboards containing views with shared functionality. First I found out how to open a different storyboard modally. But since the application uses a navigation controller at certain points, I also wanted to keep the navigation when opening some other storyboards. 

So iOS makes it really simple:

First instantiate the storyboard you want to navigate to (bundle can be nil if the story board is in the same bundle):

UIStoryboard * planningSB = [UIStoryboardstoryboardWithName:@"PlanningStoryboard"bundle:nil];

Then instantiate the initial view controller:

UIViewController * planningVC = [planningSB instantiateInitialViewController];

And last, just push this view controller into the view controllers collection of the current navigation controller.

[self.navigationControllerpushViewController:planningVC animated:YES];

Now the View controller of the second storyboard is loaded in the navigation controller. When pushed on the back arrow on the top, it will simply go back to the previous view controller and the second story board will be deallocated when the reference to its initial view controller is released.

Next is another example where I change the transition style:

UIStoryboard * planningSB = [UIStoryboardstoryboardWithName:@"PlanningStoryboard"bundle:nil];

UIViewController * planningVC = [planningSB instantiateInitialViewController];

 

[UIView transitionWithView:self.view duration:0.8 options:UIViewAnimationOptionTransitionCrossDissolve

                        animations:^{

                            [self.navigationController pushViewController:planningVC animated:NO];

                        }

                        completion:NULL];

 

 In my case I had a camera view that could be called from several views, I put this on a new storyboard and this works great. Since the camera view was also pointing to the search order view, I had to put the search order view also on a separate storyboard. Again my main story board got simpler.

So have a main story board, and separate as much as you can onto separate storyboards. I made a general class StoryBoardNavigation where I centralized all functions to call child storyboards.

Here is an example of this:

This function navigates to the storyboard called OrderLookupStoryboard and opens the view in start position.

+(void)NavigateToOrderLookupFrom:(UIViewController*)vc {UIStoryboard* sb =[UIStoryboard storyboardWithName:@"OrderLookupStoryboard" bundle:nil];UIViewController* vcTo =[sb instantiateInitialViewController];[UIView transitionWithView:vc.view duration:0.8 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{[vc.navigationController pushViewController:vcTo animated:NO];} completion:NULL];}

This function passes some parameters to the storyboard.

+(void)NavigateToCameraFrom:(UIViewController*)vc WithSelectedZone:(int)selectedZone {UIStoryboard* sb =[UIStoryboard storyboardWithName:@"CameraStoryboard" bundle:nil];MediaCapture* vcTo =[sb instantiateInitialViewController]; vcTo.selectedZone = selectedZone; vcTo.zoneSet = YES;[UIView transitionWithView:vc.view duration:0.8 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{[vc.navigationController pushViewController:vcTo animated:NO];} completion:NULL];}

This function opens the view in module transition style:

+(void)NavigateToSignatureFrom:(UIViewController*)vc withSignee:(NSString*)Signee{UIStoryboard* sb =[UIStoryboard storyboardWithName:@"SignatureStoryboard" bundle:nil];UIViewController* vcTo =[sb instantiateInitialViewController];((SignatureVC*) vcTo).Signee=Signee;[vcTo setModalTransitionStyle:UIModalTransitionStylePartialCurl];[vc presentViewController:vcTo animated:YES completion:nil]; 

} 

 

 

 

 


Locating the Configuration file of an VSTO (excel) project

I was contacting WCF Webservices in an Excel VSTO project. Deploying this to the customers, they could use VBA as much as they want without exposing code to contact the database.  

My problem was that the message size was the default and therefore not enough. It was already deployed to a customer and he had already made a lot of changes. Re deploying would mean losing these changes. So I was planning on changing the binding on the client and server. There came the challenge. Changing it on the server was no problem, but finding the config file on the client was a BIG problem.

The path was located at: C:\Users\mderaeve\AppData\Local\Apps\2.0\V154RLC4.47N\73GCM0NZ.LX6\poed..vsto_268646e17c0b18d5_0001.0000_9bd2d9b28f73af10

Fortunatelly, there are not that many directories in the Local\Apps\2.0 so you can find the project fast. I found the path by putting this piece of code in the project and show it somewhere in the excel. Then I installed it and the path was printed out.

//Get the assembly information

System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();

                   

//Location is where the assembly is run from

string assemblyLocation = assemblyInfo.Location;

 

//CodeBase is the location of the ClickOnce deployment files

Uri uriCodeBase = new Uri(assemblyInfo.CodeBase);

string ClickOnceLocation = Path.GetDirectoryName(uriCodeBase.LocalPath.ToString());

Excel._Worksheet activeSheet = ((Excel._Worksheet)Application.ActiveSheet);

 

activeSheet.Cells[4, 2] = ClickOnceLocation;


iOS: Performing a segue using a splash screen.

My application was using a dash board, from where the user navigates through the application. Works file until some large forms take more then a second or so to load. Then it might appear that the form is doing nothing. So a simple solution is to show a waiting screen while performing the segue. The only little trick is that you call the perform segue with a delay and before you do that show your waiting screen. Else the thread will wait to output to GUI until the segue is done and you will not see the splash screen.

So here just a little piece of code:

-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath

{

    @try

    {

        NSString * label = [store.HomeButtonsArray objectAtIndex:indexPath.item];

        //Show the waiting popup (Change it here to match your waiting popup)

        hud = [GeneralFunctionsGetMBProgressHUDForView:self.view];

        hud.detailsLabelText = [[storeTranslate: @"$MOB$Loading"] stringByAppendingString:[@" : "stringByAppendingString:label]];

        AudioServicesPlaySystemSound(0x450);

        

        [self performSelector:@selector(segueWithLabel:) withObject:label afterDelay:0.2];

        //[self performSegueWithIdentifier:[NSString stringWithFormat:@"DashB%@",label] sender:nil];

    }

    @catch (NSException *exception) {

        

    }

    @finally {

        

    }

}

 

-(void) segueWithLabel:(id) label

{

    [selfperformSegueWithIdentifier:[NSStringstringWithFormat:@"DashB%@",label] sender:nil];

}

 
if a collection view item is pressed, the segue starts after 0.2 seconds, but first a waiting popup will be send to the screen.
Then when the view disappears, I hide the waiting popup:
 

-(void) viewDidDisappear:(BOOL)animated

{

    [MBProgressHUDhideAllHUDsForView:self.viewanimated:YES];

}




iOS: UITextView Maximum length in TableView or Collection View

I was using a UITextView with a custom layout that shows the borders like a textfield. I also needed a fixed length, to use in a collection view. Off course they didn't provide this simple feature. So I implemented it myself. For starters I added an extra property to my custom TextView: MaxLength. By default its 0 and when its 0, the text will be unlimited. If I set it to more then 0 the text will be limited to this number.

#import <UIKit/UIKit.h>

 

@interface MyTextView : UITextView

 

@property int MaxLength;

 

@end

In the initializer I set this property to 0, also I add the borders so it looks like a normal textfield:

- (id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super initWithCoder:aDecoder];

    if (self) {

        // Initialization code

        [GeneralFunctionsMakeTextField:self];

        self.MaxLength=0;

    }

    returnself;

}

(Here's the MakeTextField function for those who are interested:)

+(void) MakeTextField:(UITextView *) vw

{

    vw.backgroundColor = [UIColorclearColor];

    UIImageView *borderView = [[UIImageViewalloc] initWithFrame: CGRectMake(0, 0, vw.frame.size.width, vw.frame.size.height)];

    borderView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    UIImage *textFieldImage = [[UIImageimageNamed:@"TextField.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 8, 15, 8)];

    borderView.image = textFieldImage;

    [vw addSubview: borderView];

    [vw sendSubviewToBack: borderView];

}

Now I implement the UITextViewDelegate on the control where it's used (I've set the MaxLength property using the runtime attributes in the attribute inspector of the story board):

-(BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{

    if ([textView isKindOfClass:[MyTextView class]] && ((MyTextView *)textView).MaxLength>0 )

    {

        NSUInteger newLength = [textView.text length] + [text length] - range.length;

        return (newLength > ((MyTextView *)textView).MaxLength) ? NO : YES;

    }

    else

    {

        return YES;

    }

}

 

 


iOS: UITable view (Server Side) Lazy Loading

I'm creating an app that will be used in factories. At the test factories, the application runs fast and smooth. But when starting to deploy to other factories where the workflow is different, I had some grids with loading times of 5 to 7 seconds. They didn't liked it and so did I. So then I had to build in paging in the grids. Since I'm working with a .Net backend server, I will post this answer using LINQ on the server and iOS on the app.

The solution is to show the first 50 elements in the grid, when the 50st element is shown, he has to get the next 50 element and so on... The implementation is actually very simple. I pass the itemCount and the pageSize to the server. So you will need to add these arguments to the getter of your data. On server side I just add a simple Skip and Take using link. Skip the first ... items and Take the (pageCount) number of items. Thats it. So it took me 30 minutes to implement it for the first grid, the next will be 5 minutes of work. 

First on the app side, add this variable

int iPageSize=0;

Then in the CellForRowAtIndexPath method you''l need to check the number of items and load the following items before you return the cell. The store.PageItemCount is a global variable that defines the max items per page, I made it global so it can be used on all grids and variable so we can change the item size on the device.

int indexRow = indexPath.row+1;

int iPageSizeSum = iPageSize+store.PageItemCount;

if (indexRow >= iPageSizeSum)

{

    iPageSize = iPageSize + store.PageItemCount;

    [self configureView];

}

 

in the configureView I add the items to a mutable array and reload the table:

    

[self.ordersOnJig addObjectsFromArray:(NSMutableArray *) value];

[self.locationsTable reloadData];

[self.locationsTable reloadInputViews];

Now the server side integration is even more simple:

returnList = returnList.Skip(skip).Take(pageSize).ToList();

return returnList;



iOS: Nice popup menu havely based on LeveyPopListView

I the ActionSheet menu just isn't cool enough for you, then try this. I got the code form Levey. Just adapted the sizing of the popup, and that's it.

First a teaser that looks like this:

 

The code is very simple. It will create a rectangle, show a title header on top and a UITableView on the bottom. You can use the Cell layout from the table view, lke adding images and subtitles very easy. You can download the code here: https://github.com/levey/LeveyPopListView

The only small chagens I make was the color and the size and adding an image on the far right of the title. Changes made in: LeveyPopListView.m and the LeveyPopListView.h

This reflects in the change of the 2 initializers where I add the image name to use for the top image. In the implementation file I put a fixed size, but you could also provide the size with the initializer for example. 

The first thing you will need to do is to fill an Array with NSDictionaries that contain the image and text for each item. In this example I add all items from the UITabbarcontroller and add 2 extra items, cancel and logout. I call this method on the ViewLoad:

-(void) FillShortMenuOptions

{

    NSMutableArray * optionsToSet = [[NSMutableArray alloc] init];

    for (UIViewController * viewController inself.viewControllers)

    {

        NSString * test = viewController.tabBarItem.title;

        UIImage * image = viewController.tabBarItem.image;

        [optionsToSet addObject:[NSDictionary dictionaryWithObjectsAndKeys:image,@"img",test,@"text", nil]];

    }

    [optionsToSet addObject:[NSDictionarydictionaryWithObjectsAndKeys:[UIImageimageNamed:@"113-navigation.png"],@"img",[[VariableStoresharedInstance] Translate:@"$MOB$Cancel"],@"text", nil]];

    [optionsToSet addObject:[NSDictionarydictionaryWithObjectsAndKeys:[UIImageimageNamed:@"54-lock.png"],@"img",[[VariableStoresharedInstance] Translate:@"$MOB$LogOut"],@"text", nil]];

    _options = [NSArray arrayWithArray:optionsToSet];

}

To use this control just show it on any event, for example a button click event:

lplv = [[LeveyPopListViewalloc] initWithTitle:[store Translate:@"$MOB$Menu"] options:_optionsheaderImage:@"53-house.png"];

lplv.delegate=self;

[lplvshowInView:self.viewanimated:YES];

Then Implement the delegate:

UIViewController <LeveyPopListViewDelegate>


#pragma mark - LeveyPopListView delegates

- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex

{

    //Put click logic here

    NSDictionary * item = _options[anIndex];

    NSString * itemText = item[@"text"];

}

- (void)leveyPopListViewDidCancel

{

    //Put cancel logic here

}

 

Here are the 2 changed files, first the .h and then the .m:

//

//  LeveyPopListView.h

//  LeveyPopListViewDemo

//

//  Created by Levey on 2/21/12.

//  Copyright (c) 2012 Levey. All rights reserved.

//  Modified by TheRave777 on 4/5/2012

//

 

 

@protocolLeveyPopListViewDelegate;

@interface LeveyPopListView : UIView <UITableViewDataSource, UITableViewDelegate>

 

@property (nonatomic, weak) id<LeveyPopListViewDelegate> delegate;

@property (copy, nonatomic) void(^handlerBlock)(NSInteger anIndex);

 

// The options is a NSArray, contain some NSDictionaries, the NSDictionary contain 2 keys, one is "img", another is "text".

- (id)initWithTitle:(NSString *)sTitle options:(NSArray *)aOptions headerImage:(NSString *) sHeaderImageName;

- (id)initWithTitle:(NSString *)sTitle

            options:(NSArray *)aOptions headerImage:(NSString *) sHeaderImageName

            handler:(void (^)(NSInteger anIndex))aHandlerBlock;

 

// If animated is YES, PopListView will be appeared with FadeIn effect.

- (void)showInView:(UIView *)aView animated:(BOOL)animated;

@end

 

@protocol LeveyPopListViewDelegate <NSObject>

- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex;

@optional

- (void)leveyPopListViewDidCancel;

@end

 

 

//

//  LeveyPopListView.m

//  LeveyPopListViewDemo

//

//  Created by Levey on 2/21/12.

//  Copyright (c) 2012 Levey. All rights reserved.

//  Modified by TheRave777 on 4/5/2012

//

 

#import "LeveyPopListView.h"

#import "LeveyPopListViewCell.h"

 

#define POPLISTVIEW_SCREENINSET 40.

#define POPLISTVIEW_HEADER_HEIGHT 50.

#define POPLISTVIEW_WIDTH 400.

#define POPLISTVIEW_HEIGHT 500.

#define RADIUS 5.

 

@interface LeveyPopListView (private)

- (void)fadeIn;

- (void)fadeOut;

@end

 

@implementation LeveyPopListView {

    UITableView *_tableView;

    NSString *_title;

    NSArray *_options;

    NSString * _headerImageName;

}

 

#pragma mark - initialization & cleaning up

- (id)initWithTitle:(NSString *)sTitle options:(NSArray *)aOptions headerImage:(NSString *) sHeaderImageName{

    CGRect rect = [[UIScreenmainScreen] applicationFrame];

    if (self = [super initWithFrame:rect]) {

        self.backgroundColor = [UIColorclearColor];

        _title = [sTitle copy];

        _headerImageName = [sHeaderImageName copy];

        _options = [aOptions copy];

        

        _tableView = [[UITableViewalloc] initWithFrame:CGRectMake(POPLISTVIEW_SCREENINSET

                                                                   POPLISTVIEW_SCREENINSET + POPLISTVIEW_HEADER_HEIGHT

                                                                   POPLISTVIEW_WIDTH,

                                                                   POPLISTVIEW_HEIGHT)];

        _tableView.separatorColor = [UIColorcolorWithWhite:0alpha:.2];

        _tableView.backgroundColor = [UIColorclearColor];

        _tableView.dataSource = self;

        _tableView.delegate = self;

        [self addSubview:_tableView];

    }

    return self;    

}

 

- (id)initWithTitle:(NSString *)sTitle

            options:(NSArray *)aOptions headerImage:(NSString *) sHeaderImageName 

            handler:(void (^)(NSInteger anIndex))aHandlerBlock {

    

    if(self = [self initWithTitle:sTitle options:aOptions headerImage:sHeaderImageName])

        self.handlerBlock = aHandlerBlock;

    

    returnself;

}

 

 

#pragma mark - Private Methods

- (void)fadeIn {

    self.transform = CGAffineTransformMakeScale(1.3, 1.3);

    self.alpha = 0;

    [UIViewanimateWithDuration:.35animations:^{

        self.alpha = 1;

        self.transform = CGAffineTransformMakeScale(1, 1);

    }];

 

}

- (void)fadeOut {

    [UIViewanimateWithDuration:.35animations:^{

        self.transform = CGAffineTransformMakeScale(1.3, 1.3);

        self.alpha = 0.0;

    } completion:^(BOOL finished) {

        if (finished) {

            [selfremoveFromSuperview];

        }

    }];

}

 

#pragma mark - Instance Methods

- (void)showInView:(UIView *)aView animated:(BOOL)animated {

    [aView addSubview:self];

    if (animated) {

        [self fadeIn];

    }

}

 

#pragma mark - Tableview datasource & delegates

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return_options.count;

}

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentity = @"PopListViewCell";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity];

    if (!cell)

        cell = [[LeveyPopListViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIdentity];

    

    if ([_options[indexPath.row] respondsToSelector:@selector(objectForKey:)]) {

        cell.imageView.image = _options[indexPath.row][@"img"];

        cell.textLabel.text = _options[indexPath.row][@"text"];

    } else

        cell.textLabel.text = _options[indexPath.row];

    

    return cell;

}

 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    

    // tell the delegate the selection

    if ([_delegate respondsToSelector:@selector(leveyPopListView:didSelectedIndex:)])

        [_delegateleveyPopListView:selfdidSelectedIndex:[indexPath row]];

    

    if (_handlerBlock)

        _handlerBlock(indexPath.row);

    

    // dismiss self

    [self fadeOut];

}

#pragma mark - TouchTouchTouch

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    // tell the delegate the cancellation

    if ([_delegate respondsToSelector:@selector(leveyPopListViewDidCancel)])

        [_delegateleveyPopListViewDidCancel];

    

    // dismiss self

    [self fadeOut];

}

 

#pragma mark - DrawDrawDraw

- (void)drawRect:(CGRect)rect {

 

     CGRect titleRect = CGRectMake(POPLISTVIEW_SCREENINSET + 10, POPLISTVIEW_SCREENINSET + 10 + 5,

     400, 30);

     CGRect separatorRect = CGRectMake(POPLISTVIEW_SCREENINSET, POPLISTVIEW_SCREENINSET + POPLISTVIEW_HEADER_HEIGHT - 2,400, 2);

     

     CGContextRef ctx = UIGraphicsGetCurrentContext();

     

     // Draw the background with shadow

     CGContextSetShadowWithColor(ctx, CGSizeZero, 6., [UIColorcolorWithRed:13/255.0fgreen:90/255.0fblue:168/255.0falpha:.75].CGColor);

     [[UIColorcolorWithRed:13/255.0fgreen:90/255.0fblue:168/255.0falpha:.75] setFill];

     

     

     float x = POPLISTVIEW_SCREENINSET;

     float y = POPLISTVIEW_SCREENINSET;

     float width = POPLISTVIEW_WIDTH;

    float height = POPLISTVIEW_HEIGHT + POPLISTVIEW_SCREENINSET;

    CGMutablePathRef path = CGPathCreateMutable();

CGPathMoveToPoint(path, NULL, x, y + RADIUS);

CGPathAddArcToPoint(path, NULL, x, y, x + RADIUS, y, RADIUS);

CGPathAddArcToPoint(path, NULL, x + width, y, x + width, y + RADIUS, RADIUS);

CGPathAddArcToPoint(path, NULL, x + width, y + height, x + width - RADIUS, y + height, RADIUS);

CGPathAddArcToPoint(path, NULL, x, y + height, x, y + height - RADIUS, RADIUS);

CGPathCloseSubpath(path);

CGContextAddPath(ctx, path);

    CGContextFillPath(ctx);

    CGPathRelease(path);

    

    // Draw the title and the separator with shadow

    CGContextSetShadowWithColor(ctx, CGSizeMake(0, 1), 0.5f, [UIColorblackColor].CGColor);

    [[UIColorwhiteColor] setFill];

    [_titledrawInRect:titleRect withFont:[UIFontsystemFontOfSize:17.]];

    CGRect titleImageRect = CGRectMake(392, POPLISTVIEW_SCREENINSET + 10, 25, 25);

    [[UIImageimageNamed:_headerImageName] drawInRect:titleImageRect blendMode:nilalpha:0.5];

    CGContextFillRect(ctx, separatorRect);

}

 

@end

 
Full code can be found here!