Monday, July 31, 2017

UIButton Click Not working when its triggered from static library

Leave a Comment

We are trying to trigger display button from static library project using webview. while integrating static library with single view application we have got the output design. but when we tried to attempt action by clicking on Button its not working.

Below is the code,which we have used inside cocoa touch static library

UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];  imageButton.frame = CGRectMake(self.view.frame.size.width-50, 10, 50, 50);  [imageButton setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];  imageButton.adjustsImageWhenHighlighted = NO;  // [imageButton addTarget:self  action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];  [imageButton addTarget:self action:@selector(hideWebViewBtn:) forControlEvents:UIControlEventTouchUpInside];   -(IBAction)hideWebViewBtn:(id)sender {        NSLog(@"Hide Button clicked");      [self.adView removeFromSuperview];      self.adView = nil;      return;  } 

Below is the screenshot which displayed in single view application after integration and running. Once i click on the button its not getting clicked.

enter image description here

5 Answers

Answers 1

try this,whether self button is triggering or not..

  [self.myButton sendActionsForControlEvents:UIControlEventTouchUpInside]; 

It worked for me

Answers 2

You should add your button to a super view.And also,the super view should enable user interfaces.

[yourSuperView addSubView:button];yourSuperView.userInteractionEnabled=YES;

Answers 3

How about you change your return type of your 'hideWebViewBtn' method from 'IBAction' to 'void'?

Answers 4

"Once i click on the button its not getting clicked." You mean that u click the close button,but it doesn't call the function hideWebViewBtn:() ?

Answers 5

You can try this.

UIButton *imageButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-100, 10, 50, 50)];      [imageButton setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];      [self.view addSubview:imageButton];     [self.view bringSubviewToFront:imageButton];     [imageButton removeTarget:self action:NULL forControlEvents:UIControlEventAllEvents];      [imageButton addTarget:self action:@selector(hideWebViewBtn:) forControlEvents:UIControlEventTouchUpInside]; 

Hope it works for you. Thanks!

Read More

Android push notification banner not showing up in some devices

Leave a Comment

I tried to push notify with NotificationCompat :

NotificationCompat.Builder b = new NotificationCompat.Builder(this);             b.setAutoCancel(true)                     .setDefaults(NotificationCompat.DEFAULT_ALL)                     .setWhen(System.currentTimeMillis())                     .setSmallIcon(this.getResources().                         getIdentifier("ic_launcher", "mipmap", this.getPackageName()))                     .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),                         this.getResources().                         getIdentifier("ic_launcher", "mipmap", this.getPackageName())))                     .setTicker("God Reacts")                     .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)                     .setPriority(Notification.PRIORITY_MAX)                     .setContentTitle(data.get("lineOne"))                     .setContentText(data.get("lineTwo"))                     .setContentInfo("Spread the message !");              PendingIntent contentIntent = PendingIntent.getActivity(this, 0,                     new Intent(this,getMainActivityClass()),                     PendingIntent.FLAG_UPDATE_CURRENT);             b.setContentIntent(contentIntent);             NotificationManager nm = (NotificationManager)              this.getSystemService(Context.NOTIFICATION_SERVICE);             nm.notify(1, b.build()); 

But in few devices (Samsung,MI etc) the notification banner is not shown. The notification slides in the action tray with sound and vibrate.

But in few devices it is shown perfectly when the app is closed/background/foreground.The device where it's popping up correctly uses marshmallow.Is is due to specific OS ? Or is it device related issue? What extra I need to add?

3 Answers

Answers 1

The problem may arise in some devices of nougat version due to Battery optimization.
eg. Samsung Galaxy S8 and S8+, Oneplus, xaiomi etc. but in Android version of nougat, You can try this once, for that you have to check settings once,

step 1: Goto settings >

step 2: search for "Battery optimization" >

step 3: from here, tap on "apps not optimized" and switch to "all apps."

step 4: search for your app (of which you are not getting notification)

step 5: tap on your app name and set it as not optimized so that it can receive notification.

OR

step 1: Go to Settings > Apps

step 2: Click the : Menu in top right, select > [Special Access]

step 3: Select > Optimize Battery Usage >

step 4: Click the dropdown menu towards the top of the screen that says: "Apps not optimized [v]" -> change to [All Apps]

step 5: select your app and change it "Not optimized".

Answers 2

in chinese devices like MI or OPPO ,etc . The system shut downs notification services for non-whitelisted apps .So there is nothing much you can do about it . Simply request them to whitelist your app ( bleak chance of happening in general ) or use a hack of always keeping your app in memory somehow , say by running some blank background service 24*7

Answers 3

First Try with minimum notification property . Try following code which is working fine in my app . If it works than you can debug your code by enabling on by one property of notification .

 private void sendNotification(String messageBody) { Intent intent = new Intent(this, NotificationActivity.class);     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,             PendingIntent.FLAG_ONE_SHOT);      Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)             .setSmallIcon(R.drawable.ic_action_notification)             .setContentTitle("Touchrooms Notification")             .setContentText(messageBody)             .setAutoCancel(true)             .setSound(defaultSoundUri)             .setContentIntent(pendingIntent);      NotificationManager notificationManager =             (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);      notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());  } 
Read More

How to set X-Frame Options to ALLOW-FROM https://example.com and SAMEORIGIN on server

Leave a Comment

I have a requirement to set the X-Frame options on the server level to either:

Understand that X-Frame Options are mutually exclusive. See here.

However, my application requires framing in https://example.com and also from its SAMEORIGIN.

Please advise if there is a way around this while retainining my application's requirement to having allow framing on the same origin and be framed on 1 external site.

Or is this impossible?

1 Answers

Answers 1

In addition to only supporting one instance of the header, X-Frame-Options does not support any more than just one site, SAMEORIGIN or not.

You'll have to use Content-Security-Policy and frame-ancestors, which does support multiple origins, like so:

Content-Security-Policy: frame-ancestors 'self' https://example.com 

A couple notes to bear in mind:

Read More

Do I need to stop a method that's running in a UI thread?

Leave a Comment

My application looks like this:

App class:

protected override void OnStart() {    MainPage = new Japanese.MainPage(); } 

MainPage class:

var phrasesPage = new NavigationPage(new PhrasesPage()) {    Title = "Play",    Icon = "play.png" }; Children.Add(phrasesPage); 

PhrasesPage class:

protected override void OnAppearing() {    base.OnAppearing();    phrasesFrame = new PhrasesFrame(this);    phrasesStackLayout.Children.Add(phrasesFrame); }  protected override void OnDisappearing() {    base.OnDisappearing();    phrasesStackLayout.Children.Remove(phrasesFrame); } 

PhrasesFrame class:

public PhrasesFrame(PhrasesPage phrasesPage) {    InitializeComponent();    Device.BeginInvokeOnMainThread(() => ShowCards().ContinueWith((arg) => { })); }  public async Task ShowCards() {    while (true)    {       // information displayed on screen here and screen       // responds to user clicks       await Task.Delay(1000);     } } 

Two questions here.

Firstly my ShowCards method has no return as it loops around until a user clicks on another icon on the bottom of the screen to select another screen. In this case what should I code for the return value. As it is the IDE warns that the method never reaches the end or a return statement. How can I fix this problem.

Second related question. As the ShowCards runs on another thread, should I do something to cancel it when the user clicks on another icon to display another screen.

I hope someone can help give me some advice. Please ask if something is not clear so I can try to make the question more clear. Thanks

2 Answers

Answers 1

The IDE is warning you that the method never reaches the end because it indeed never reaches the end, and as written your task will run forever (or at least until the application closes).

The standard way to allow a running task to be interrupted is to supply a CancellationToken when you create the task. You obtain the token from a CancellationTokenSource, give the token to the task, and then call Cancel() on the CancellationTokenSource to set the CancellationToken.IsCancellationRequested property to true, indicating to the task that it should end.

In your case you could have something like:

CancellationTokenSource cts new CancellationTokenSource();  public PhrasesFrame(PhrasesPage phrasesPage) {    InitializeComponent();    Device.BeginInvokeOnMainThread(() => ShowCards(cts.Token).ContinueWith((arg) => { })); }  public Disappearing() {     cts.Cancel(); }  public async Task ShowCards(CancellationToken ct) {    while (!ct.IsCancellationRequested)    {       // information displayed on screen here and screen       // responds to user clicks       await Task.Delay(1000, ct);     } } 

And then call Disappearing() when you wish to end your task.

Answers 2

You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle/

var cancelToken = new CancellationTokenSource(); Task.Factory.StartNew(async () => {     await Task.Delay(10000);     // call web API }, cancelToken.Token);  //this stops the Task: cancelToken.Cancel(false); 

Anther solution is user Timer in Xamarin.Forms, stop timer when you want https://xamarinhelp.com/xamarin-forms-timer/

Read More

Support multiple iOS SDK versions when nullability of a protocol changes

Leave a Comment

The MCSessionDelegate protocol has changed in iOS 11 from

- (void)                    session:(MCSession *)session  didFinishReceivingResourceWithName:(NSString *)resourceName                            fromPeer:(MCPeerID *)peerID                               atURL:(NSURL *)localURL                           withError:(nullable NSError *)error; 

to

- (void)                    session:(MCSession *)session  didFinishReceivingResourceWithName:(NSString *)resourceName                            fromPeer:(MCPeerID *)peerID                               atURL:(nullable NSURL *)localURL                           withError:(nullable NSError *)error; 

This causes that, when implementing this delegate in Swift, using

func session(_ session: MCSession,              didFinishReceivingResourceWithName resourceName: String,              fromPeer peerID: MCPeerID,              at localURL: URL?,              withError error: Error?) {} 

won't compile on Xcode 8; and

func session(_ session: MCSession,              didFinishReceivingResourceWithName resourceName: String,              fromPeer peerID: MCPeerID,              at localURL: URL,              withError error: Error?) {} 

won't compile on Xcode 9.

In both cases Xcode shows this error:

Parameter of 'session(_:didFinishReceivingResourceWithName:fromPeer:at:withError:)' has different optionality than required by protocol 'MCSessionDelegate'


How to make it compile on both versions?

2 Answers

Answers 1

To improve code with mix & match of XCode versions , you can put check for swift versions like

#if swift(>=2.3) let specifier = url.resourceSpecifier ?? "" #else let specifier = url.resourceSpecifier #endif 

But here’s a little helper that might be useful ..found on http://radex.io/xcode7-xcode8/:

func optionalize<T>(x: T?) -> T? {     return x } 

I know, it’s a little weird. Perhaps it will be easier to explain if you first see the result:

let URL = optionalize(url) ?? "" // works on both versions! 

We’re taking advantage of Optional lifting to get rid of ugly conditional compilation at call site. See, what the optionalize() function does is it turns whatever you pass in into an Optional, unless it’s already an Optional, in which case, it just returns the argument as-is. This way, regardless if the url is optional (Xcode 8) or not (Xcode 7), the “optionalized” version is always the same.

(To explain in more detail: in Swift, Foo can be considered a subtype of Foo?, since you can wrap any value of Foo in an Optional without loss of information. And since the compiler knows about this, it allows you to pass a non-optional in place of an optional argument — lifting Foo into Foo?.)

Answers 2

I don't see why this is a problem.

If you build with Xcode 8, you can use the old method signature, build you app and submit it to the AppStore. The app will be built against the iOS10 SDK, and will run on iOS10 and iOS11 devices.

When you switch to Xcode 9, you can switch to the new method signature, and (when Xcode 9 is out of beta) submit to the AppStore. The app is built against iOS11 SDK and will run on iOS11 devices.

The only difficulty is that brief period when you might want to use both Xcode 8 (to release app updates now) and Xcode 9 (preparing for app releases after iOS11 is released). You'd need to have a separate iOS11 branch in your git repo - but you'll be doing that anyway, right?

Read More

intellij: how to deploy to two folders?

Leave a Comment

The general question is: how to work with many different git repos at the same time in one intellij project. Where the git repos need to be inside the main application (that is one git repo too). I cannot use symlinks because I cannot commit those

I have 2 git repos

one is for the main app, the other one is for a library I am using in several projects.

Here is how it goes: I have the main app. Via composer I add my library / package to the application.

The problem:

folder structure:

to develop

IdeaProjects/myappA

note: there is are as well IdeaProjects myappB etc

IdeaProjects/mylib

in myappA there is

IdeaProjects/myappA/vendor/mylib

server deploy folder:

/var/www/www.myappA.com/

I do a lot of changes to the library, I have it open as another module when I work on myappA so I do code changes to mylib in that folder / module that actually contains the original source code of mylib. Now i don't want to composer install or update each time I do a tiny change. So what I do is I deploy via intellij the files from the library mylib each time on save directly into the composer install folder of my main application e.g. to IdeaProjects/myappA/vendor/mylib. Now the problem is, I need to deploy it as well to the server deployment folder. But there seems no way to deploy files to two folders out of the box with intellij.

What else can I do?

currently I manually use a short key to trigger an ant build that then copies the folder IdeaProjects/myappA/vendor/mylib to the server deployment directory.

2 Answers

Answers 1

There are multiple solutions depending on your setup:

solution inside intellij: just import mylib as a module inside your myapp project Go to File > Project Settings > Modules, click the + and choose import module import module

git native solution: Use submodules

Submodules allow you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate.

Note that there are some quirks when working with submodules, especially the way to keep the referenced submodules up-to-date

For completeness: if you were using gradle or maven instead of ant, you could use their respective projects views and use the + to add multiple build.gradle or pom.xml files, which would automatically import those projects as modules into intellij.

Answers 2

I think the module approach does fit your case and yes you can have a different git repo per module. Right click on your project root new->module or file->new module from existing source

Intellij should also detect every git repository automatically in your project if you check Settings | Version Control you should see the list.

You can also speed up some operations such as git pull instead of having to pull from every repository (VCS -> Git -> Pull) you can do VCS -> Update Project or ctrl-t (cmd-t on mac)

Read More

Swift error when running pod lib lint

Leave a Comment

Swift is very new for me so please excuse me if this is a very basic question. I have a swift project that builds fine in xcode and all the unit tests pass.

However when I run pod lib lint i get a no such module MyModule error.

Testing with xcodebuild.  -> my-swift-project (0.4.2) - WARN  | source: Git SSH URLs will NOT work for people behind firewalls configured to only allow HTTP, therefore HTTPS is preferred. - ERROR | [iOS] xcodebuild: Returned an unsuccessful exit code. - ERROR | [iOS] xcodebuild:  my-swift-project/Echo/Delegates/MyModule/MyModule.swift:7:8: error: no such module 'MyModule' 

The file in question has an import module declaration at the top of the file

import MyModule 

Would anyone know why this would be happening and why the project builds in xcode fine but not when i get to this stage?

Any help appreciated

Thanks

1 Answers

Answers 1

build settings > Framework Search Paths Set framework search path to $(SRCROOT) and recursive.

Read More

No Code Completion or Syntax Highlighting in Xcode Unit Test Target with “Defined Module” enabled

Leave a Comment

We have a project with a Unit Test target that has "Defines Module" enabled, due to a mix of Objective C and Swift. With that setting enabled, syntax highlighting and code completion stops for all non-language items. IE code completion will list language level stuff like NS_ENUM and for loop, but not NSString and not any of our classes.

The same thing happens if I create a new project, set "Defines Module" to YES. Syntax Highlighting and Code Completion fails in the Unit Test Code, set it to NO it starts working again.

We have tried all the usual ways to get things to work, Deleting "Derived Data", Checking/Unchecking "Suggest Completions While typing" and "Enable type-over Completions", deleting "~/Library/Caches/com.apple.dt.Xcode", deleting items in var/folders/, adding some clean up scripts to the post build phase, setting the main target to "Defines Module" as well, and of course endless restarts of Xcode and macOS.

I have repo'd this on 3 different Macs (Sierra) with Xcode 8.3.2 and Xcode 8.2. I have one team member that is not having this issue and the only real difference seems to be that he's still on El Cap.

Here is a list of some of the things we've tried:

Xcode 8 syntax highlighting doesn't work

How to Empty Caches and Clean All Targets Xcode 4

Xcode 8.2 Code Completion Not Working

One Weird Trick to Fix Autocomplete in Xcode

Apple Dev Forums

Has anybody had luck with getting this to work (other than turning off "Defines Module" in the Test Target)? My next step is to file a Radar.

1 Answers

Answers 1

Looks like you have arm64 in your Debug configuration for Valid Architectures. May be because of that you are getting this error. Try removing arm64 on your valid architecture inside debug configuration and try building it.

Read More

MyModel.objects.update_or_create() --> Boolean wether data was updated or not?

Leave a Comment

AFAIK Django does not provide a generic way to see if data was changed by update_or_create()

The boolean created tells me that a row was created. But how can I know if data was changed (SQL UPDATE which changed data)

Example:

obj, created = MyModel.update_or_create(pk=12345,                        defaults=dict(name='Doctor Zhivago')) 

There are three cases:

  1. obj was created. No problem, I have the boolean variable created
  2. obj was not created, it was updated. For example the previous name was "Machuca".
  3. obj was not created and not updated. For example the previous name was already "Doctor Zhivago".

I can't distinguish between case2 and case3 at the moment.

3 Answers

Answers 1

Feeling a bit inspired by @bakkal, I've written a mixin class that you can apply to a custom Manager class, then assign that custom Manager to your MyModel class. This changes the format of the returned tuple to (obj, created, updated). In the loop over the values in defaults.items() I am checking if any of the new values are different from the old values.

class UpdateOrCreateMixin(object):     def update_or_create_v2(self, defaults=None, **kwargs):         """         Look up an object with the given kwargs, updating one with defaults         if it exists, otherwise create a new one.         Return a tuple (object, created, updated), where created and updated are          booleans specifying whether an object was created.         """         defaults = defaults or {}         lookup, params = self._extract_model_params(defaults, **kwargs)         self._for_write = True         with transaction.atomic(using=self.db):             try:                 obj = self.select_for_update().get(**lookup)             except self.model.DoesNotExist:                 obj, created = self._create_object_from_params(lookup, params)                 if created:                     return obj, created, False             updated = False             for k, v in defaults.items():                 oldattr = getattr(obj, k)                 if oldattr != (v() if callable(v) else v):                     updated = True                 setattr(obj, k, v() if callable(v) else v)             obj.save(using=self.db)         return obj, False, updated  class CustomManager(UpdateOrCreateMixin, models.Manager):     pass  class MyModel(models.Model)     field = models.CharField(max_length=32)     objects = CustomManager()  obj, created, updated = MyModel.objects.update_or_create_v2(pk=12345,                    defaults=dict(name='Doctor Zhivago')) 

Answers 2

Given how that interface is implemented, there's no way to tell if the object has been updated or not if it's created. Because it always calls save() in that case.

Here's how update_or_create() is currently implemented:

    with transaction.atomic(using=self.db):         try:             obj = self.select_for_update().get(**lookup)         except self.model.DoesNotExist:             obj, created = self._create_object_from_params(lookup, params)             if created:                 return obj, created          # [below part always runs the same if obj was not created]         for k, v in defaults.items():             setattr(obj, k, v() if callable(v) else v)         obj.save(using=self.db)     return obj, False 

Ref. https://github.com/django/django/blob/master/django/db/models/query.py#L459

As you can see when the object is not created, the way it's implemented can't tell if it was updated or not.

However you could manually verify if your lookup/update values are different from those on the existing object in the DB before caling save(), and then set an updated flag.

Answers 3

I'm currently using mixed approach to handling this type of tasks:

I have last_edited or last_modified field on model without auto_now=True.

Instead of auto_now I use django-dirtyfields and inside save method I do something like this:

def save(*args, **kwargs):     if self.is_dirty():         self.last_modified = now()     super().save(*args, **kwargs) 

If you don't like the mess in save method, you can use pre_save signal and update last_modified there based on dirty fields.

Then after calling update_or_create you can pretty safely rely on last_modified field in order to check if model was indeed modified.

dirtyfield's api is pretty simple, you can play with it without too much setup pain.

Read More

node.js compressing ZIP to memory

Leave a Comment

I want to zip some data into a writableStream.

the purpose is to do all in memory and not to create an actual zip file on disk.

For testing only, i'm creating a ZIP file on disk. But when I try to open output.zip i get the following error: "the archive is either in unknown format or damaged". (WinZip at Windows 7 and also a similar error on MAC)

What am I doing wrong?

const   fs = require('fs'),     archiver = require('archiver'),     streamBuffers = require('stream-buffers');  let outputStreamBuffer = new streamBuffers.WritableStreamBuffer({     initialSize: (1000 * 1024),   // start at 1000 kilobytes.     incrementAmount: (1000 * 1024) // grow by 1000 kilobytes each time buffer overflows. });  let archive = archiver('zip', {     zlib: { level: 9 } // Sets the compression level. }); archive.pipe(outputStreamBuffer);  archive.append("this is a test", { name: "test.txt"}); archive.finalize();  outputStreamBuffer.end();  fs.writeFile('output.zip', outputStreamBuffer.getContents(), function() { console.log('done!'); }); 

1 Answers

Answers 1

You are not waiting for the content to be written to the output stream.

Comment out outputStreamBuffer.end(); from your code and change it to the following...

outputStreamBuffer.on('finish', function () {     fs.writeFile('output.zip', outputStreamBuffer.getContents(), function() {          console.log('done!');     }); }); 
Read More

SSIS Script Component Cannot Load Assembly Until Manually Opened

Leave a Comment

I am creating a SSIS project via Biml (Using the current version of BimlExpress per the Varigence BimlExpress page) that uses a script component within a Data Flow Task. The project is created without issue however errors when it gets to the Script Component:

Could not load file or assembly 'Microsoft.SqlServer.DTSPipelineWrap, Version=14.100.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

at ScriptMain.PreExecute() at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PreExecute()

I can see this dll within the GAC and when I try to add the reference manually, SSIS states that I can't add it as it is already included in the project.

However, if I open the Script Component and manually Build it - but change nothing else - the Data Flow Task will run through without issue.

To clarify, I know I have changed nothing else as I am recreating this project from the Biml each time I want to test a new approach, which provides a consistent baseline.


Does anyone know why a Script Component that includes a reference to a GAC dll, will only work when manually Built but not beforehand?

I have used this exact Biml before without issue, though on a different environment. Worked using Visual Studio 2012 against a SQL Server 2016 instance yet doesn't here within Visual Studio 2015 (targeting 2012) against a SQL Server 2016 instance.

For further context I have also tested this outputting the SSIS Project targeted at SQL Server 2012, 2014 and 2016 with the exact same error message.


Update

This appears to definitely be a dll version problem in the project as output from BimlExpress, in that if I manually create the v4.0_14.100.0.0__89845dcd8080cc91 folder with the version 13 dll inside at C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SqlServer.DTSPipelineWrap the script component now errors out with the following:

System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.SqlServer.Dts.Pipeline.Wrapper.IDTSComponentMetaData100'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{ID removed just in case}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.HandleUserException(Exception e)

at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PreExecute()

at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostPreExecute(IDTSManagedComponentWrapper100 wrapper)

1 Answers

Answers 1

I guess your problem may be related to the Express version.

See at the related page the differences between Express and BimlStudio versions (Feature Comparison Chart under "Compare with BimlStudio" button):

https://www.varigence.com/BimlExpress

Read More

Sunday, July 30, 2017

How do we track the user flow in a website that doesn't have an authentication system?

Leave a Comment

Let's say the customer filled a form on the 3rd page he visited, how do we find out his flow.(Where did he come from, which links on the website he clicked, basically the entire flow till he filled in the form).

There is no login or any kind of authentication system on the website. Is there a way to monitor the user flow? I don't have much experience with google analytics. Can anyone help me with this?

3 Answers

Answers 1

There are two options to do this:

1) User Reports

See video: https://www.youtube.com/watch?v=Y_OiIyLC4cI - From @Ramankingdom comment

Go to Google Analytics > Audience > User explorer. Create a custom segment for your form of interest (in terms of the event data), e.g. Advance Conditions > Filter Sessions to Include > Event Category Contains Forms > Event Action Contains My Form of Interest

The resulting window will show you each Client ID, the number of sessions each client has had, session duration.. etc, as well as goal conversion rate. Note that this is the overall goal conversion rate, and is not specific to a specified goal.

You can then explore the clients behavior across sessions and within session, and have a list of specific interactions that Google Analytics captured.

2) Custom Reports

The second option is to export all behavior using your Client, Session and Timestamp custom dimensions. For this you will need to create a custom report for the Three custom dimensions along with Page Path.

Once you have exported the page path data, you will need to repeat for events (as they need to be queried separately).

Once you have the exported data, you can then join your datasets and have a full csv output of each of your sessions. This then gives you the ability to review the process data of any session containing any interaction of interest.

This method is more complicated, but will provide you with more flexability in the long run.

Limitations: This will be constrained to the data that has been sent to GA. I.e if links are not tracked, you will not be able to determine every link the user clicked.

--- Update ---

If you want to understand the flow of a particular user, specific to an email enquiry or lead, then you will also need to capture a unique identifier. For example, you could have a hidden field with a randomly generated number. This randomly generated number would then be sent along with the email. In addition, this randomly generated number should be captured with the email enquiry event, allowing you to identify specific email enquiries, whilst abiding by the PII terms of GA.

Answers 2

I think you may need a little help from the developer, I would do the following:

1 - detect IP address using PHP : $_SERVER['REMOTE_ADDR'] more about IP address reading from PHP : How to get the client IP address in PHP?

2 - Reading the REFERER page in PHP I would use: $_SERVER['HTTP_REFERER'] , this will tell you what is the previous page that the user had clicked in to reach this page,

3- Set a Unique session using PHP and store the REFERER page on it incrementally along with the IP address More about sessions in PHP: https://www.w3schools.com/php/php_sessions.asp

4- Store the above in a mysql DB and create a view for it using one of the Charts libraries

Answers 3

You need to start using google analytics and google tag manager

You can generate cutom report related to user flow ,device ,location etc.

The Users Flow report is a graphical representation of the paths users took through your site, from the source, through the various pages, and where along their paths they exited your site. The Users Flow report lets you compare volumes of traffic from different sources, examine traffic patterns through your site, and troubleshoot the efficacy of your site.

you can find more details here

Go to analytics

enter image description here

find the page you want stats on where visitors went next. To do that, you need to click on that page and select "Explore traffic through here", which ultimately leads to another flow visualisation, but only includes traffic going to and from that page:

enter image description here

enter image description here

You an also define your custom events and get all information related to user.

Read More

No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available

Leave a Comment

In Java project, I am using Sprig Boot 1.5.3.RELEASE. It is connecting with two databases i.e. MongoDB and Microsoft SQLServer. When I run it with spring-boot:run goal, it works fine. However, when I try to run it with package goal then below error is reported by test cases despite the fact that those test cases are not connecting to SQL Server database:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}     at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)     at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)     at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)     at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)     at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)     at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)     .....     ..... 

MediationTest.java (Java class containing test cases generating above error)

@RunWith(SpringRunner.class) @DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class) @SpringBootTest(classes = { Application.class }) public class MediationTest {      @Autowired     private SwiftFormat swiftFormat;     ......................     ...................... 

MsqlDbConfig.java

@Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "msqlEntityManagerFactory", transactionManagerRef = "msqlTransactionManager", basePackages = { "com.msql.data" }) public class MsqlDbConfig {      @Bean(name = "msqlDataSource")     @ConfigurationProperties(prefix = "msql.datasource")     public DataSource dataSource() {         return DataSourceBuilder.create().build();     }      @Bean(name = "msqlEntityManagerFactory")     public LocalContainerEntityManagerFactoryBean msqlEntityManagerFactory(             EntityManagerFactoryBuilder builder,             @Qualifier("msqlDataSource") DataSource dataSource) {         return builder.dataSource(dataSource)                 .packages("com.utils.msql.info")                 .persistenceUnit("msql").build();     }      @Bean(name = "msqlTransactionManager")     public PlatformTransactionManager msqlTransactionManager(             @Qualifier("msqlEntityManagerFactory") EntityManagerFactory msqlEntityManagerFactory) {         return new JpaTransactionManager(msqlEntityManagerFactory);     } } 

application.properties

spring.data.mongodb.uri=mongodb://dev-abc-123:27017/db  msql.datasource.url=jdbc:sqlserver://ABC-SQL14-WXX;databaseName=dev msql.datasource.username=dev msql.datasource.password=***** msql.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver msql.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy spring.jpa.show-sql=true 

1 Answers

Answers 1

The spring-boot:run goal is defined by the Mojo included within the spring-boot-maven-plugin project. You can find it here. https://github.com/spring-projects/spring-boot/blob/8e3baf3130220a331d540cb07e1aca263b721b38/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java.

The requiresDependencyResolution scope is set to Test. This will include the dependencies from each phase on the classpath. Take a look at the specification here. https://maven.apache.org/developers/mojo-api-specification.html

The package goal provided by Maven wouldn't include these additional dependencies on the classpath and I believe that is the cause of your issues.

Spring Boot provides a repackage goal which is what should be used for building out executable spring-boot applications.

However, to get more to the point. I think if you update your test to exclude an additional class it might fix your problem.

@DataMongoTest(excludeAutoConfiguration = {EmbeddedMongoAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

Read More

List all gif files in photo library

Leave a Comment

I have a requirement in which the user needs to fetch a gif from a list of gif files in library. I tried to fetch both images & Videos without any issue. But when I used kUTTypeGIF as media, it crashes with error :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'No available types for source 0'

Here is my code:

#import "ViewController.h" #import <MobileCoreServices/MobileCoreServices.h>  @interface ViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>  @end  @implementation ViewController  - (void)viewDidLoad {     [super viewDidLoad]; }  -(IBAction)btnChooseGif:(id)sender {     UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];     imagePicker.delegate = self;     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;     imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeGIF, nil];   // Here is the crash      [self presentViewController:imagePicker animated:YES completion:nil]; }  -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {  } @end 

How can i solve this? And if kUTTypeGIF media is not supported here, how can i show the list all gif files to the user for choosing one? I need to display gif files only in the UIImagePickerController

2 Answers

Answers 1

iOS does not give you an easy way to determine -- while using UIImagePickerController -- what the underlying file format is for the pictures stored in the camera roll. Apple's philosophy here is that an image should be thought of as a UIImage object and that you should not care what the ultimate file format is.

So, since you can not use UIImagePickerController to filter out GIF files. Here's a couple possibilities for you:

1 )

Once you pick an image, you can determine what kind of file it is. Here's an example question that asks how to determine if the image is a PNG or JPEG. Once the user picks a file, you'll know whether it's a GIF or a JPEG or a PNG or whatever.

2 )

You could convert any UIImage to a GIF file. Here's a question that points to a library that might be able to help.

3 )

You could iterate across the entire camera roll and convert/save those images into your app's documents directory as GIF files. Something that starts with enumeration found in this related question and then runs each picture through the ImageIO framework to convert it to a gif file (the code for which I pointed out in solution # 2). You can then roll your own picker.

p.s. your own code wasn't going to work because, as Nathan pointed out, gif is not a media type. This is a function that points out the available media types:

-(IBAction)btnChooseGif:(id)sender {     NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypePhotoLibrary];      NSLog(@"availableMedia is %@", availableMedia);      UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];     imagePicker.delegate = self;     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;      imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];     [self presentViewController:imagePicker animated:YES completion:nil]; } 

Answers 2

If you only want to fetch assets from Photos library without picker, you can use PHFetchResult for getting array of PHAsset. Below is the list of available MediaType enums available in Photos.Framework:

typedef NS_ENUM(NSInteger, PHAssetMediaType) { PHAssetMediaTypeUnknown = 0, PHAssetMediaTypeImage   = 1, PHAssetMediaTypeVideo   = 2, PHAssetMediaTypeAudio   = 3, } PHOTOS_ENUM_AVAILABLE_IOS_TVOS(8_0, 10_0); 

You can use it as :

PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil]; 

and request image from asset as :

PHImageManager *manager = [PHImageManager defaultManager];      PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];     requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;     requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;     requestOptions.synchronous = true;  [manager requestImageDataForAsset:asset options:requestOptions resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {  NSLog(@"Data UTI :%@ \t Info :%@",dataUTI,info);             }]; 

Hope this will help you!!

Read More

Spring boot test does not respect web security configuration

Leave a Comment

I'm writing test for a Rest API controller. This endpoint is accessible without any authorization:

@EnableWebSecurity @Configuration @Import(AppConfig.class) class WebSecurityConfig extends WebSecurityConfigurerAdapter {  @Autowired  private UserDetailsRepository accountRepository;  @Autowired private CustomUserDetailsService customUserDetailsService;  @Autowired private JWTAuthenticationFilter jwtAuthenticationFilter;  @Override protected void configure(HttpSecurity http) throws Exception {     http         .csrf().disable()         .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)         .authorizeRequests()             .anyRequest().authenticated().and()         .sessionManagement()             .sessionCreationPolicy(SessionCreationPolicy.STATELESS); }  /*  * Apparently, permitAll() doesn't work for custom filters, therefore we ignore the signup and login endpoints   * here  */ @Override public void configure(WebSecurity web)         throws Exception {     web.ignoring()         .antMatchers(HttpMethod.POST, "/login")         .antMatchers(HttpMethod.POST, "/signup"); }  /*  * set user details services and password encoder  */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {     auth.userDetailsService(userDetailsServiceBean()).passwordEncoder(passwordEncoder()); }  @Bean public PasswordEncoder passwordEncoder() {     return new BCryptPasswordEncoder(); }  /* Stopping spring from adding filter by default */ @Bean public FilterRegistrationBean rolesAuthenticationFilterRegistrationDisable(JWTAuthenticationFilter filter) {     FilterRegistrationBean registration = new FilterRegistrationBean(filter);     registration.setEnabled(false);     return registration; } 

}

The JWTAuthenticationFilter class:

@Component public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {      @Autowired     private UserDetailsService customUserDetailsService;      private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);     private final static UrlPathHelper urlPathHelper = new UrlPathHelper();      final static String defaultFilterProcessesUrl = "/**";      public JWTAuthenticationFilter() {         super(defaultFilterProcessesUrl);         super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl)); //Authentication will only be initiated for the request url matching this pattern         setAuthenticationManager(new NoOpAuthenticationManager());     }      @Override     public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {         Authentication authentication = AuthenticationService.getAuthentication(request, customUserDetailsService);         return getAuthenticationManager().authenticate(authentication);     }      @Override     protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {         logger.debug("failed authentication while attempting to access "+ urlPathHelper.getPathWithinApplication((HttpServletRequest) request));         response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Authentication Failed");     }      @Override     protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {         SecurityContextHolder.getContext().setAuthentication(authResult);         chain.doFilter(request, response);     }      @Override     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {         super.doFilter(req, res, chain);     } }  

When I make a request (using postman) to 'signup' endpoint it works fine. But when I run the test, it hits doFilter and fails, as it doesn't get authenticated.

@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class AuthenticationControllerFTest {      @Autowired      private MockMvc mockMvc;      @MockBean     private AuthenticationManager authenticationManager;      @Test     public void testCreate() throws Exception {         Authentication authentication = Mockito.mock(Authentication.class);         Mockito.when(authentication.getName()).thenReturn("DUMMY_USERNAME");         Mockito.when(                 authenticationManager.authenticate(Mockito                         .any(UsernamePasswordAuthenticationToken.class)))                 .thenReturn(authentication);          String exampleUserInfo = "{\"name\":\"Test1234\",\"username\":\"test@test.com\",\"password\":\"Salam12345\"}";         RequestBuilder requestBuilder = MockMvcRequestBuilders                 .post("/signup")                 .accept(MediaType.APPLICATION_JSON).content(exampleUserInfo)                 .contentType(MediaType.APPLICATION_JSON);          MvcResult result = mockMvc.perform(requestBuilder).andReturn();          MockHttpServletResponse response = result.getResponse();         int status = response.getStatus();         String content = response.getContentAsString();         System.out.println(content);         Assert.assertEquals("http response status is wrong", 200, status);     } } 

Any idea on how to fix this issue ?

2 Answers

Answers 1

The issue was resolved by adding the following code to the test class:

@Autowired private WebApplicationContext context;  @Autowired private Filter springSecurityFilterChain;  @Before public void setup() {     mockMvc = MockMvcBuilders.webAppContextSetup(context)             .addFilters(springSecurityFilterChain).build(); } 

Answers 2

@Override protected void configure(HttpSecurity http) throws Exception {     http.csrf().disable().authorizeRequests()             .antMatchers("/**").permitAll()             .anyRequest().authenticated(); } 
Read More

Hibernate not getting correct records using query.list();

Leave a Comment

I'm building an application that uses Hibernate and Mysql, My entire databse has 15 tables.

Here is the problem: I start inserting records into the database and viewing them using query.list(); to get the added records, howerver after a while of getting "correct" results, I start not having the last record I added, I add again and it's the same(the one that was showing before shows but not the last one I added), I refresh and I get the right records, I refresh again and I get 32 records instead of 43, I'm not using any complicated queries just a Select with a condition, as you can see this is really weird.

Note that I'm saving the objects and then imidiately fetching, so an insert directly followed by a select(I don't know if that can cause problems in Mysql), the records are also added into the databse perfectly, using Mysql workbench I can see that my records are added corretly into the database, I really hope someone can atleast help me debug this, because I'm not getting any errors.

I'm using Hibernate 4.3.10 and java version 1.8.0_131

Here is a piece of code that "sometimes" gives me problems when getting the results from one of the entities that I use:

getting a list of Products:

public static List<Product> productsList() {         //singleton factory object         SessionsGenerator FactoryObject = new SessionsGenerator();         Session session = SessionsGenerator.getFactory().openSession();         List<Product> list = new ArrayList<>();         try {             list = session.createQuery("from Product where deleted= false").list();             System.out.println("-------------- list product: "+list); // testing from console here I get the same results on the user interface, so it can't be a Javafx problem.         } finally {             session.close();         }         return list;     } 

Code for inserting a product:

public static boolean SaveOrUpdate(Product product) {         SessionsGenerator FactoryObject = new SessionsGenerator();         Session session = SessionsGenerator.getFactory().openSession();         try {             session.beginTransaction();             session.saveOrUpdate(product);             session.getTransaction().commit();         } catch (Exception e) {             return false;         } finally {             session.close();             return true;         }     } 

Here is the Product entity class:

@Entity @Table(name = "Product") public class Product{     @Id     @GeneratedValue(strategy = GenerationType.AUTO)     @Column(name = "id", nullable = false)     int id;     @Column(name = "code", nullable = false)     String code;     @Column(name = "matricule", nullable = false)     String matricule;     @Column(name = "marque", nullable = false)     String marque;     @Column(name = "type", nullable = false)     String type;     @OneToMany(targetEntity = Facture.class, mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)     private List<Facture> factures;     @OneToMany(targetEntity = Achat.class, mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)     private List<Achat> achats;     @Column(name = "deleted", nullable = false)     boolean deleted;      public Product() {     }      public Product(String code, String matricule, String marque,String type) {         this.code = code;         this.matricule = matricule;         this.marque = marque;         this.type = type;         this.deleted = false;     } //setters and getters 

Here is my hibernate configuration file:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>   <session-factory>     <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>     <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>     <property name="hibernate.connection.username">root</property>     <property name="hibernate.connection.password">root</property>     <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/gestioncommerciale</property>     <property name="connection_pool_size">1</property>     <property name="hbm2ddl.auto">update</property>     <property name="show_sql">true</property>     <property name="hibernate.current_session_context_class">thread</property>   </session-factory> </hibernate-configuration> 

Edit: I tried session.flush() and session.clear(), cause I though the problem has to do with cashing, but I still have the same problem, I'm starting to think this is a problem with the Mysql Workbench server.

It has been five days, I can't believe no one in the entire stackoverflow community even has the slightest idea about this, this is as strange as the problem I'm having.

2 Answers

Answers 1

I think random result is due to lack of transaction boundary for your select statement. According to this hibernate doc, you should

Always use clear transaction boundaries, even for read-only operations

Try to change your code and check the result.

Transaction tx = null; try {     tx = session.beginTransaction();     list = session.createQuery("from Product where deleted= false").list();     tx.commit(); } catch (Exception e) {       if (tx != null) tx.rollback(); } finally {       session.close(); } 

A detailed discussion could be found here

Answers 2

It's definitely strange that this is happening. At first glance, the code seems fine and I don't see any issues with how you're fetching the data.

You mentioned that you are getting the correct responses in the beginning but then after awhile the incorrect data is returned.

I think this is because you're creating a new session each time and not actually closing it once you're done.

Basically, change this:

SessionsGenerator.getFactory().openSession(); 

To:

SessionsGenerator.getFactory().getCurrentSession(); 

When using openSession(), you need to explicitly flush and close the object. This may be the cause of your problem.

getCurrentSession() opens a new session if one does not exist and also automatically flushes and closes the session once done.

Also, add this into your hibernate.cfg.xml

<session-factory> <!--  Put other elements here --> <property name="hibernate.current_session_context_class">           thread </property> </session-factory> 

otherwise, you'll get exceptions occurring because you haven't configured to use getCurrentSession properly.

Additionally, try calling

session.flush();  session.close();  

instead, if you don't want to take the above approach.

Hopefully, that fixes the issue!

Read More

Default UICollectionView layout not respecting iPad split screen

Leave a Comment

My layout when on split screen is not respecting the width of the split screen.

My custom view is respecting it(the black bar at the top) but anything using autolayout is not respecting the width.

I am handling rotation using

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { 

Is there a helper method for handling split view? Do I handle it in layoutSubview? I would have expected the UICollectionView to handle this for us.

In viewWillTransition I use

  guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {             return         }    flowLayout.invalidateLayout() 

enter image description here

1 Answers

Answers 1

I assume by "default" layout you mean a UICollectionViewFlowLayout. It looks like the itemSize width is bigger then the width of the view. Try adding a check in collectionView:layout:sizeForItemAtIndexPath: to make sure that the width is less than or equal to the collection's width.

Read More

Why is a .crash log showing crash in UIPresentationController but my app doesn't use UIPresentationController?

Leave a Comment

I've got an app in the app store and there's a crash report showing there's a very occasional crash with details below:

Incident Identifier: C25BD8DF-FAA9-4A5F-B3D2-6E1CE81F1D17 CrashReporter Key:   798f7dee81117ed0f05b3f19dc4bbc2874eefaf6 Hardware Model:      iPhone9,2 Process:             My app [1936] Path:                /private/var/containers/Bundle/Application/757D7BE6-4F91-4B74-BA64-09FA53AE3E16/My app.app/My app Identifier:          com.app.Myapp Version:             12 (1.1) Code Type:           ARM-64 (Native) Role:                Foreground Parent Process:      launchd [1] Coalition:           com.app.Myapp [701]   Date/Time:           2017-06-27 20:05:28.7901 -0400 Launch Time:         2017-06-27 16:38:23.0376 -0400 OS Version:          iPhone OS 10.3.2 (14F89) Report Version:      104  Exception Type:  EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000010 Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [0] Triggered by Thread:  0  Thread 0 name: Thread 0 Crashed: 0   UIKit                           0x0000000190ee4264 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 444 (UIPresentationController.m:731) 1   UIKit                           0x0000000190ee4260 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 440 (UIPresentationController.m:731) 2   UIKit                           0x0000000190e20950 _runAfterCACommitDeferredBlocks + 292 (UIApplication.m:2469) 3   UIKit                           0x0000000190e129ec _cleanUpAfterCAFlushAndRunDeferredBlocks + 528 (UIApplication.m:2447) 4   UIKit                           0x0000000190b86648 _afterCACommitHandler + 132 (UIApplication.m:2499) 5   CoreFoundation                  0x000000018aa109a8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32 (CFRunLoop.c:1802) 6   CoreFoundation                  0x000000018aa0e630 __CFRunLoopDoObservers + 372 (CFRunLoop.c:1898) 7   CoreFoundation                  0x000000018aa0ea7c __CFRunLoopRun + 956 (CFRunLoop.c:2849) 8   CoreFoundation                  0x000000018a93eda4 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3113) 9   GraphicsServices                0x000000018c3a8074 GSEventRunModal + 100 (GSEvent.c:2245) 10  UIKit                           0x0000000190bf9058 UIApplicationMain + 208 (UIApplication.m:4089) 11  My app                          0x000000010005a8b4 main + 56 (Database.swift:17) 12  libdyld.dylib                   0x000000018994d59c start + 4 

My app doesn't use UIPresentationController so why is this showing as the last line in Thread 0 which is the thread that crashed?

1 Answers

Answers 1

Without looking at your code exactly this is quite hard to answer. Commonly, you should check possible classes (including system frameworks) that you might ignore are actually a subclass of UIPresentationController. In addition, a 3rd party library might be referencing this class (or subclass).

However most likely is that this is a crash in UIKit. UIPresentationController is a class that provides advanced view controller management and handles transitioning between controllers. Most likely, UIKit is crashing somewhere (very possibly due to your code). More info in the Apple docs.

Read More

Error when trying to open my asp.net 4.5 MVC web application using VS 2012. Asp.net has not been registered on the server

Leave a Comment

I have a Windows Server 2012 R2 & Visual Studio Professional 2012. now i use to develop an asp.net 4.5 mvc 4 web application without any problem. but now when i try to open the project i will get this error:-

enter image description here

if i click OK then this error:-

enter image description here

if i click OK the visual studio will stop working

enter image description here

so can anyone adivce what is going on ??

and here is how the Turn windows features on/off looks like:- enter image description here

Now i did this modification, as i read on a post in the internet that deleting the cache might help. so i removed this folder:-

%LocalAppData%\Microsoft\VisualStudio\11.0\ComponentModelCache 

then i tried to open the Visual Studio, and i got the same 2 errors, but the visual studio did not stop working, and i was able to modify the code i rebuild the project and run it.. so not sure what is going on ?

5 Answers

Answers 1

In order to resolve this error you have to install related version of .Net framework in your system.

First install IIS if not installed.

Then run following command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i 

OR (Depens on your OS)

C:\Windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis -i 

And in IIS your site should run on pool with version like : .Net FrameWork v4.0.xxxxxx

Answers 2

aspnet_regiis -i 

Using the ASP.NET IIS Registration tool, you can perform tasks such as the following:
Register or remove the .NET Framework ASP.NET installation with IIS.
Create new ASP.NET application pools.
Display the status of all installed versions of ASP.NET.
More here

Edit 1:-

dism /online /enable-feature /featurename:IIS-ASPNET45 /all 

Try running this command

Edit 2:-

Try downloading and installing this update

This is a related tweet

If you get KB3002339 hanging kill the VSUpdate process in task manager. Windows Update will finish. Bing/Google KB3002339 install manually. https://twitter.com/blowdart/status/542542342075346945

Answers 3

See if the computer has self updated to .NET 4.6 (due to Windows Update task). In some situations, the installation of .NET 4.6 may impact on Visual Studio 2012.

In my case I had to upgrade my project to NET 4.6 to solve the problem.

In relation to IIS itself, I guess you may be forgotten some feature - as HTTP which I guess is necessary, even if you won't utilize it directly. Check all features and toogle OFF just those really optional (like FTP).

Answers 4

This reminds me of similar issues I have seen in the past and I strongly suspect it's an installation order related thing which ultimately boils down to the aspnet_regiis command which has been mentioned already (here's some more information on this topic: https://rockyprogress.wordpress.com/2011/09/06/iis-7-5-and-net-framework-4-installation-order-does-matter/).

You would generally want to install IIS first and then .NET afterwards. So I suggest you get rid of the .NET 4.5 installation again by using the "Turn Windows Features On/Off" screen and then later simply add it back in.

Answers 5

Please try below point

1) open Visual studio run as administration

2) Please host your site in IIS (Not on port like localhost:65389...)

3) Make sure about application pool (with framework 4.0)

4) run C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i command

Read More

coded ui test project, obtain value of asp label

Leave a Comment

Created a simple calculator app in webforms. User enters a number in a text field MainContent_numberTb and clicks on results button.

Added a new 'coded UI Test Project' to my solution. Have tested the UI by adding '5', This all works fine. Would now like to compare the actual result against the expected result.

BrowserWindow Browser = BrowserWindow.Launch("http://url");  UITestControl UiInputField = new UITestControl(Browser); UiInputField.TechnologyName = "Web"; UiInputField.SearchProperties.Add("ControlType", "Edit"); UiInputField.SearchProperties.Add("Id", "MainContent_numberTb");  //Populate input field Keyboard.SendKeys(UiInputField, "5");  //Results Button UITestControl ResultsBtn = new UITestControl(Browser); ResultsBtn.TechnologyName = "Web"; ResultsBtn.SearchProperties.Add("ControlType", "Button"); ResultsBtn.SearchProperties.Add("Id", "MainContent_calBtn");  Mouse.Click(ResultsBtn); 

All above code works fine, problem occurs when trying to access the label

<asp:Label ID="AllNumLbl_Res" runat="server"></asp:Label> 

What do I insert beside control type? It's not edit as edit is the text field. Then also, what stores the actual result so I can compare AllNumsTB?

string expectedAllNums = "1, 2, 3, 4, 5"; UITestControl AllNumsTB = new UITestControl(Browser); AllNumsTB.TechnologyName = "Web"; AllNumsTB.SearchProperties.Add("ControlType", "?????"); AllNumsTB.SearchProperties.Add("Id", "MainContent_AllNumLbl_Res");  if(expectedAllNums != AllNumsTB.??????) {     Assert.Fail("Wrong Answer"); } 

UPDATE OK so using the debugger console I was able to get the value of the label using ((Microsoft.VisualStudio.TestTools.UITesting.HtmlControls.HtmlSpan)new System.Collections.ArrayList.ArrayListDebugView(((System.Collections.CollectionBase)(AllNumsTB.FindMatchingControls()).List).InnerList).Items[0]).DisplayText

but when I use this in the code & ArrayListDebugView are inaccessible due to protection??

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// UPDATE Thanks K Scandrett for the answer...If I may I was wondering could you also please help me with the validation...If the user enters a letter or a non positive number the error message will fire..

<asp:RegularExpressionValidator ID="regexpName"   //VALIDATION MESSAGE                 UITestControl PositiveNumValMsg = new UITestControl(Browser);                 PositiveNumValMsg.TechnologyName = "Web";                 PositiveNumValMsg.SearchProperties.Add("Id", "MainContent_regexpName"); 

This all works fine, however I want to test if the label appears or not...so far I have tried

//bool visible = false;             //System.Drawing.Point p;              //// If the control is offscreen, bring it into the viewport             //PositiveNumValMsg.EnsureClickable();              //    // Now check the coordinates of the clickable point             //    visible = PositiveNumValMsg.TryGetClickablePoint(out p)             //        && (p.X > 0 || p.Y > 0);              var isVisible = PositiveNumValMsg.WaitForControlPropertyNotEqual(UITestControl.PropertyNames.State, ControlStates.Invisible); 

but they all return true even when the label is not shown, but it is still on the page just set to invisible. In that case I should check its style..something like

//string labelText3 = PositiveNumValMsg.GetProperty("style").ToString(); 

then check if the style contains visibility: visible?

1 Answers

Answers 1

You want to grab its InnerText property.

It's not mandatory to set ControlType, so some variation of the following should work:

UITestControl AllNumsTB = new UITestControl(Browser); AllNumsTB.TechnologyName = "Web"; AllNumsTB.SearchProperties.Add(HtmlControl.PropertyNames.Id, "MainContent_AllNumLbl_Res");  var result = AllNumsTB.GetProperty(HtmlLabel.InnerText).Trim(); // var result = AllNumsTB.GetProperty("InnerText").Trim(); 

OR from https://social.msdn.microsoft.com/Forums/en-US/69ea15e3-dcfa-4d51-bb6e-31e63deb0ace/how-to-read-dynamic-text-from-label-using-coded-ui-for-web-application?forum=vstest:

var AllNumsTB = new HtmlLabel(Browser); AllNumsTB.TechnologyName = "Web"; AllNumsTB.SearchProperties.Add(HtmlControl.PropertyNames.Id, "MainContent_AllNumLbl_Res"); var result = AllNumsTB.InnerText;  string result2;  // you may need to include this section, or you may not if (result.Length > 0) {     AllNumsTB.WaitForControlReady();     result2 = AllNumsTB.InnerText; } 

EDIT: Regarding testing an ASP.Net Validator

I've been able to check whether the validator message is displayed with the following method:

1) Created a test asp.net page with a regex validator that requires exactly 2 digits:

<asp:TextBox ID="numberTb" runat="server"></asp:TextBox> <asp:RegularExpressionValidator ID="regexpName" ControlToValidate="numberTb" ValidationExpression="\d{2}" runat="server" ErrorMessage="Please enter 2 digits"></asp:RegularExpressionValidator> <asp:Button ID="Button1" runat="server" Text="Button" /> 

2) Ran the Coded UI Test builder and started recording => Clicked Input box; typed s; hit tab (the validator error message is showing).

3) Paused the Recorder.

4) Clicked "Generate Code" icon and give it a method name; clicked "Add and Generate" button.

5) Now I dragged and dropped the Crosshair icon onto the validator message. Scrolling down the list of options is the ControlDefinition. Right-clicked it and selected "Add Assertion...".

6) Changed the Comparator to "Contains"; the Comparison Value to " visible;"; and gave it an Assertion Failure message.

7) Clicked the "Generate Code" icon, gave it a method name, etc.

Now we have code that will test the validator by running two methods - first to enter the input and trigger (or not) the validator message; the second to test the validator's message visibility. I copied and pasted the generated code and used it to write another opposing test using " hidden;" when given correct input. Ran both tests, and they both passed.

You will end up with something like (have substituted values):

public void DigitValidatorMsgShownWithIncorrectStringInput() {     #region Variable Declarations     HtmlSpan uIAtleast2digitsPane = this.UIHomePageMyASPNETApplWindow.UIHomePageMyASPNETApplDocument.UIAtleast2digitsPane;     #endregion      // Verify that the 'ControlDefinition' property of 'At least 2 digits' pane contains ' visible;'     StringAssert.Contains(uIAtleast2digitsPane.ControlDefinition, " visible;", "The validator was not shown"); } 

Of course all this can be coded manually once you know what you're looking for.

Read More

Saturday, July 29, 2017

How can I run a method in the background on my Xamarin app?

Leave a Comment

Once the app is open and running I would like a background process to check a database and to make an update depending on the data in the database. I would like to make this check every one minute. I only want this to happen when the app is in the foreground and in view of the user.

Can someone give me some suggestions as to how I do this? I assume I can call a method from here but I'm not sure how to do this. Also I do not know how to stop or even if I need to manually cancel / stop the process. Would it cancel itself when the app is not in the foreground and restart when the app came back into the foreground?

public partial class App : Application {     protected override void OnStart()    {       App.DB.InitData();       MainPage = new Japanese.MainPage();    } 

But do I need to make this run on a different thread and if so how could I do that.

Sorry if my question is not clear. Please ask and I can update if it doesn't make sense.

7 Answers

Answers 1

What we did in our forms application was to make use of the Device.Timer and the Stopwatch class that available in System.Diagnostics, and Xamarin.Forms to create a very generic managed timer that we could interact with using the onStart, onSleep and onResume methods in Xamarin.Forms.

This particular solution doesn't require any special platform specific logic, and the device timer and stopwatch are non UI blocking.

using Xamarin.Forms; using System; using System.Linq; using System.Diagnostics;  namespace YourNamespace {     public partial class App : Application     {         private static Stopwatch stopWatch = new Stopwatch();         private const int defaultTimespan = 1;          protected override void OnStart()         {             // On start runs when your application launches from a closed state,               if (!StopWatch.IsRunning)             {                 StopWatch.Start();             }              Device.StartTimer(new TimeSpan(0, 0, 1), () =>             {                 // Logic for logging out if the device is inactive for a period of time.                  if (StopWatch.IsRunning && StopWatch.Elapsed.Minutes >= defaultTimespan)                 {                     //prepare to perform your data pull here as we have hit the 1 minute mark                             // Perform your long running operations here.                          InvokeOnMainThread(()=>{                             // If you need to do anything with your UI, you need to wrap it in this.                         });                      stopwatch.Restart();                 }                  // Always return true as to keep our device timer running.                 return true;             });         }          protected override void OnSleep()         {             // Ensure our stopwatch is reset so the elapsed time is 0.             StopWatch.Reset();         }          protected override void OnResume()         {             // App enters the foreground so start our stopwatch again.             StopWatch.Start();         }     } } 

EDIT:

To give some context as to how the above solution works step by step:

The application starts from a closed state and the 'OnStart()' method creates our Device.Timer that ticks every second. It also starts our stopwatch that counts upto a minute.

When the app goes into the background it hits the 'OnSleep' method at this point if we were to pass a 'false' value into our Device.StartTimer() action it would not start up again. So instead we simply reset our stopwatch ready for when the app is opened again.

When the app comes back into the foreground it hits the 'OnResume' method, which simply starts the existing stopwatch.

Answers 2

you can use this,

 System.Threading.Task.Run(() =>  {       //Add your code here.  }).ConfigureAwait(false); 

Answers 3

To run a background task use a Service. Generally classifies tasks as either Long Running Tasks or Periodic Tasks.

The code for service in android look like this

[Service] public class PeriodicService : Service {      public override IBinder OnBind(Intent intent)     {         return null;     }      public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)     {         // From shared code or in your PCL           return StartCommandResult.NotSticky;     } } 

And to invoke the service in background

   var intent = new Intent (this, typeof(PeriodicService));    StartService(intent); 

In case wants to invoke and check after every minute

private void StartBackgroundDataRefreshService () {     var pt = new PeriodicTask.Builder ()         .SetPeriod (1800) // in seconds; minimum is 30 seconds         .SetService (Java.Lang.Class.FromType (typeof(BackgroundService)))         .SetRequiredNetwork (0)         .SetTag (your package name) // package name         .Build ();          GcmNetworkManager.GetInstance (this).Schedule (pt); } 

In order to know which service type is good for you read this tutorial Types of Services

Xamarin Blog for periodic background service Xamarin Service Blog

The other example is

public class PeriodicService : Service {   private static Timer timer = new Timer();        public override IBinder OnBind(Intent intent)     {         return null;     }      public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)     {         timer.scheduleAtFixedRate(new mainTask(), 0, 5000);         return StartCommandResult.NotSticky;     }     private class mainTask extends TimerTask     {          public void run()          {          //your code         }     }  } 

Here is Sample Code of XAMARIN Android Service Which will perform task after every 10 Seconds

using System; using System.Threading; using Android.App; using Android.Content; using Android.OS; using Android.Util;  namespace SimpleService {  [Service] public class SimpleStartedService : Service {     static readonly string TAG = "X:" + typeof(SimpleStartedService).Name;     static readonly int TimerWait = 10000;     Timer timer;     DateTime startTime;     bool isStarted = false;      public override void OnCreate()     {         base.OnCreate();     }      public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)     {         Log.Debug(TAG, $"OnStartCommand called at {startTime}, flags={flags}, startid={startId}");         if (isStarted)         {             TimeSpan runtime = DateTime.UtcNow.Subtract(startTime);             Log.Debug(TAG, $"This service was already started, it's been running for {runtime:c}.");         }         else         {             startTime = DateTime.UtcNow;             Log.Debug(TAG, $"Starting the service, at {startTime}.");             timer = new Timer(HandleTimerCallback, startTime, 0, TimerWait);             isStarted = true;         }         return StartCommandResult.NotSticky;     }      public override IBinder OnBind(Intent intent)     {         // This is a started service, not a bound service, so we just return null.         return null;     }       public override void OnDestroy()     {         timer.Dispose();         timer = null;         isStarted = false;          TimeSpan runtime = DateTime.UtcNow.Subtract(startTime);         Log.Debug(TAG, $"Simple Service destroyed at {DateTime.UtcNow} after running for {runtime:c}.");         base.OnDestroy();     }      void HandleTimerCallback(object state)     {         TimeSpan runTime = DateTime.UtcNow.Subtract(startTime);         Log.Debug(TAG, $"This service has been running for {runTime:c} (since ${state})." );     } } 

}

Answers 4

There are a few ways to do this in both iOS and Android. In Xamarin Forms most of this functionality falls under the moniker of Backgrounding. There are a lot of tutorials out there. This one is quite elaborate and definitely worth checking out:

http://arteksoftware.com/backgrounding-with-xamarin-forms/

In Android a lot of this work is done in a Background Service. For iOS look into Long Running or Finite-Length Tasks. As you can tell from this there is no Xamarin Forms way of doing this. You will need to write Xamarin.Android and Xamarin.iOS specific code.

Answers 5

You can use

Device.StartTimer(TimeSpan.FromMinutes(1), () => {    var shouldTimerContinueWork = true;    /*your code*/    return shouldTimerContinueWork; }); 

This timer runs on background thread, uses devices clock and reentrance safe.
To stop this timer when app is in background you can use Xamarin.Forms.Application methods OnSleep and OnResume as described here

Answers 6

I'm doing something like this is my Xamarin Forms apps.

public void execute()         {             var thread = new Thread(new ThreadStart(startAuthenticationProcess))             {                 IsBackground = true             };             thread.Start();         }  private void startAuthenticationProcess()         {             Thread.Sleep(2000);             if (!Utils.isNetworkAvailable(splashActivity))             {                 splashActivity.RunOnUiThread(() => Utils.showToast(splashActivity, splashActivity.GetString(Resource.String.r30025)));                 splashActivity.FinishAffinity();             }             else             {                 try                 {                     if (StringUtils.isBlank(strIPAdd) || (StringUtils.isNotBlank(strIPAdd) && (StringUtils.isBlank(strDbName) || "site".Equals(strDbName,StringComparison.OrdinalIgnoreCase))))                     {                         splashActivity.RunOnUiThread(() => DependencyService.Get<IAuthenticationDialog>().showAuthenticationDialog(new Command(() =>                         {                             var intent = new Intent(splashActivity, typeof(MainActivity));                             intent.PutExtra("startLoginActivity", false);                             splashActivity.StartActivity(intent);                             splashActivity.Finish();                         })));                     }                     else                     {                         gotoLoginScreen();                     }                 }                 catch (Exception e)                 {                     Log.Error(TAG, e.Message);                 }             }         } 

Answers 7

Easy, try something like this and implement your logic in those methods:

public partial class App : Application {     protected override void OnStart()    {       // Your App On start code should be here...        // and then:       Task.Run(() =>         {             //Add your code here, it might looks like:             CheckDatabase();             MakeAnUpdateDependingOnDatabase();         });    } 

I hope it helps.

Read More

Why can't I display prediction column of Spark MultilayerPerceptronClassifier?

Leave a Comment

I am using Spark's MultilayerPerceptronClassifier. This generates a column 'predicted' in 'predictions'. When I try to show it I get the error:

SparkException: Failed to execute user defined function($anonfun$1: (vector) => double) ... Caused by: java.lang.IllegalArgumentException: requirement failed: A & B Dimension mismatch! 

Other columns, for example, vector display OK. Part of predictions schema:

|-- vector: vector (nullable = true) |-- prediction: double (nullable = true) 

My code is:

//racist is boolean, needs to be string: val train2 = train.withColumn("racist", 'racist.cast("String")) val test2 = test.withColumn("racist", 'racist.cast("String"))  val indexer = new StringIndexer().setInputCol("racist").setOutputCol("indexracist")  val word2Vec = new Word2Vec().setInputCol("lemma").setOutputCol("vector") //.setVectorSize(3).setMinCount(0)  val layers = Array[Int](4,5, 2)  val mpc = new MultilayerPerceptronClassifier().setLayers(layers).setBlockSize(128).setSeed(1234L).setMaxIter(100).setFeaturesCol("vector").setLabelCol("indexracist")  val pipeline = new Pipeline().setStages(Array(indexer, word2Vec, mpc))  val model = pipeline.fit(train2)  val predictions = model.transform(test2)  predictions.select("prediction").show() 

EDIT the proposed similar question's problem was

val layers = Array[Int](0, 0, 0, 0)  

which is not the case here, nor is it the same error.

EDIT AGAIN: part0 of train and test are saved in PARQUET format here.

1 Answers

Answers 1

The addition of .setVectorSize(3).setMinCount(0) and changnig val layers = Array[Int](3,5, 2) made it work:

val word2Vec = new Word2Vec().setInputCol("lemma").setOutputCol("vector").setVectorSize(3).setMinCount(0)  // specify layers for the neural network: // input layer of size 4 (features), two intermediate of size 5 and 4 // and output of size 3 (classes) val layers = Array[Int](3,5, 2) 
Read More