How to run select "Import by Scenario" scenario -> press "Prepare&Import" from code?
I have tried this:
var importGraph = PX.Data.PXGraph.CreateInstance<SYImportProcessSingle>();
SYMappingActive mapactive = PXSelect<SYMappingActive>.Search<SYMappingActive.mappingID>(importGraph, importproviderID);
importGraph.PrepareImport.PressButton();
but this did not work to run "Prepare & Import" for "import by scenario" graph for my DAC.
First thing to check. Can you execute the import scenario from the application instance? I refer to the Process Import Scenario screen (SM206036). The provider error could be that the import scenario has no data provider assigned, or the provider is not usable.
Here is example how you can do it. I have written this for SalesOrder but you can modify it for any other screen. Also if there exist more than one Import Scenario for the same screen this code will use first Active one.
public class SOOrderEntry_Extension : PXGraphExtension<SOOrderEntry>
{
#region Actions
public PXAction<SOOrder> RunScenario;
[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "RUN")]
protected void runScenario()
{
var importGraph = PXGraph.CreateInstance<SYImportProcessSingle>();
var myMapping = PXSelect<SYMapping, Where<SYMapping.screenID, Equal<Required<SYMapping.screenID>>>>.Select(importGraph, Base.Accessinfo.ScreenID.Replace(".", string.Empty));
if (myMapping.Any())
{
importGraph.MappingsSingle.Current = importGraph.MappingsSingle.Search<SYMappingActive.name>(((SYMapping)myMapping.First(x => ((SYMapping)x).IsActive ?? false)).Name);
importGraph.Prepare.Press();
PXLongOperation.WaitCompletion(importGraph.UID);
importGraph.Clear(PXClearOption.ClearAll);
importGraph.MappingsSingle.Current = importGraph.MappingsSingle.Search<SYMappingActive.name>(((SYMapping)myMapping.First(x => ((SYMapping)x).IsActive ?? false)).Name);
importGraph.Import.Press();
PXLongOperation.WaitCompletion(importGraph.UID);
}
}
#endregion
}
Related
So I am writing a Blazor webassembly application, with asp.ner core Identity. I need to get the ID of the current user, not the username that the methods in Identy give.
The method
Context. User.identity.name
gives the username but I need the ID for a fk in a model/table.
I can't use the username as usernames might change.
I have searched the net, however I keep seeing just the username returned.
Any assistance will be greatly appreciated.
I use this with the boiler plate Identity Server:
#page "/claims"
#inject AuthenticationStateProvider AuthenticationStateProvider
<h3>ClaimsPrincipal Data</h3>
<p>#_authMessage</p>
#if (_claims.Count() > 0)
{
<table class="table">
#foreach (var claim in _claims)
{
<tr>
<td>#claim.Type</td>
<td>#claim.Value</td>
</tr>
}
</table>
}
<p>#_userId</p>
#code {
private string _authMessage;
private string _userId;
private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();
protected override async Task OnParametersSetAsync()
{
await GetClaimsPrincipalData();
await base.OnParametersSetAsync();
}
private async Task GetClaimsPrincipalData()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
_authMessage = $"{user.Identity.Name} is authenticated.";
_claims = user.Claims;
_userId = $"User Id: {user.FindFirst(c => c.Type == "sub")?.Value}";
}
else
{
_authMessage = "The user is NOT authenticated.";
}
}
}
In Startup.cs, add the following line in ConfigureServices
services.AddHttpContextAccessor();
In your Blazor component, add the following lines on the top of the file
#using System.Security.Claims
#inject IHttpContextAccessor HttpContextAccessor
In your method, add the following lines to get the UserId
var principal = HttpContextAccessor.HttpContext.User;
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
Not an answer, just a tip on using breakpoints to find the answer. My site is Blazor Server, so it's very possible that things are different-- in my case, Brian Parker's solution didn't work for me, so I did the following:
var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
if (true) {} // or any other code here, breakpoint this line
If you set a breakpoint right after retrieving the user, run the app and hover the user variable in the code when it breaks, it will pop up the complete object. By hovering various fields, you can investigate. I found that the claim type strings were big long things like "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
So the answer that worked for me was:
var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
string userId = user.FindFirst(c => c.Type.Contains("nameidentifier"))?.Value;
My point is that when the docs are complicated, or when the technology is changing fast so that one day's right answer is the next day's wrong lead, you can achieve a lot just by using VS to dig around.
Hope that helps someone. :D
The next lines work fine and I can see the whole object in the console log:
Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject)
In the console, I can see the oneProject's properties, even the name property.
Now with the following lines, the result is an error:
Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject.name)
The error is: "Cannot read property 'name' of undefined".
This is the whole code:
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { Projects } from '/imports/api/projects.js';
import ProjectFormUpdate from './ProjectFormUpdate.jsx';
export default ProjectFormUpdateContainer = withTracker(({ key1 }) => {
Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject.name)
return {
oneProject:oneProject,
};
})(ProjectFormUpdate);
A subscription in Meteor is asynchronous. This means the data is not always immediately available.
Tracker.autorun(() => {
const sub = Meteor.subscribe('projects');
if (sub.ready()){
const oneProject = Projects.findOne(key1);
console.log(oneProject.name);
}
});
will not try to find the project until the subscription is ready.
I am trying to make offline sync to table from azure mobile service. My Xamarin Form version is 1.4.2.6359.
I try to test my code in OnCreate method of MainActivity. All preparation steps such as MobileServiceClient initialization, MobileServiceSQLiteStore initialization, SyncTable creation, etc are ok.
When I try to call PullAsync, I am getting NullReferenceException. I capture the package using Package Capture App from mobile. The request goes to Azure Mobile service and it returns the correct json data successfully.
When I try the same code in Xamarin Android project (not Xamarin Form), it is working fine.
To reproduce the issue.
Just create Xamarin Form (Portable) project and use my code.
My Code
private async Task Test() {
const string applicationURL = #"https://xxxx.azure-mobile.net/";
const string applicationKey = #"xxxx";
CurrentPlatform.Init();
var client = new MobileServiceClient(applicationURL, applicationKey);
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "store.db");
if (!File.Exists(path)) {
File.Create(path).Dispose();
}
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<Product>();
await client.SyncContext.InitializeAsync(store);
var productTable = client.GetSyncTable<Product>();
try {
await client.SyncContext.PushAsync();
await productTable.PullAsync("allProducts", productTable.CreateQuery());
var t = await productTable.ToListAsync();
Console.WriteLine("Product Count : " + t.Count);
}
catch (Java.Net.MalformedURLException ex) {
Console.WriteLine(ex.Message);
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
}
References:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-xamarin-android-get-started-offline-data/
http://blogs.msdn.com/b/carlosfigueira/archive/2014/04/07/deep-dive-on-the-offline-support-in-the-azure-mobile-service-managed-client-sdk.aspx
I got the solution for this case.
As far as my understanding, this is what is happening. During the application is loading, I call PullAsync. It is async call and during this call, application keeps loading other components. The actual NullReferenceException is coming from OnPrepareOptionsMenu function (Xamarin.Forms.Platform.Android.AndroidActivity.OnPrepareOptionsMenu). The exception is happening on other thread and the thread simply dies. That's why I cannot get stack trace from my main thread.
This NullReferenceException issue is totally not related to Azure Mobile Service.
I override OnPrepareOptionsMenu in MainActivity and add try-catch block to base class function call. The problem is solved. Here is my code in MainActivity class.
public override bool OnPrepareOptionsMenu(IMenu menu) {
try {
// I am always getting menu.HasVisibleItems = false in my app
if (menu != null && menu.HasVisibleItems) {
// Exception is happening when the following code is executed
var result = base.OnPrepareOptionsMenu(menu);
return result;
}
}
catch{
}
return true;
}
I don't really understand why it is happening. Please point me out if you have better understanding of this case and better solution.
I think my issue is same as this : http://forums.xamarin.com/discussion/23579/exception-whilte-trying-to-open-activity-from-xamarin-forms-page
I am trying to make a very simple application that looks up values in a database by using polymer elements to get input.
My main polymer class looks like this:
library index;
import 'package:polymer/polymer.dart';
import 'lookup.dart';
import 'dart:html';
#CustomTag('auth-input')
class AuthInput extends PolymerElement {
#observable String username = '';
#observable String password = '';
AuthInput.created() : super.created();
void login(Event e, var detail, Node target)
{
int code = (e as KeyboardEvent).keyCode;
switch (code) {
case 13:
{
Database.lookUp(username, password);
break;
}
}
}
}
and a secondary database helper class looks like this:
library database;
import 'package:mongo_dart/mongo_dart.dart';
class Database {
static void lookUp(String username, String password) {
print("Trying to look up username: " + username + " and password: " + password);
DbCollection collection;
Db db = new Db("mongodb://127.0.0.1/main");
db.open();
collection = db.collection("auth_data");
var val = collection.findOne(where.eq("username", username));
print(val);
db.close();
}
}
I keep getting this error and I cannot think of a way around it:
The requested built-in library is not available on Dartium.'package:mongo_dart/mongo_dart.dart': error: line 6 pos 1: library handler failed
import 'dart:io';
The strange thing is, I don't want to use dart:io. The code works fine either running database processes or running polymer processes. I can't get them to work together. I don't see why this implementation of the code will not run.
The first line at https://pub.dartlang.org/packages/mongo_dart says
Server-side driver library for MongoDb implemented in pure Dart.
This means you can't use it in the browser. Your error message indicates the same. The code in the package uses dart:io and therefore can't be used in the browser.
Also mongodb://127.0.0.1/main is not an URL that can be used from within the browser.
You need a server application that does the DB access and provides an HTTP/WebSocket API to your browser client.
First time poster, but I'm really stuck.
I'm working on a little project and I'm trying to send out a tweet using a netbeans project. I'm using twitter4j and it seems like things have recently changed to where you have to use their OAuth function. I've created an application on twitter and tried some code but I keep getting this error:Exception in thread "main" connect timed outRelevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=b2b52c28 or
http://www.google.co.jp/search?q=1b442895
TwitterException{exceptionCode=[b2b52c28-1b442895 b2b52c28-1b44286b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:200)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1929)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:433)
at login.Login.start(Login.java:36)
at login.Login.main(Login.java:63)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.http.HttpClient.New(HttpClient.java:316)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
... 6 more
Java Result: 1
I'm not entirely sure what I'm doing wrong. Below is the code I've tried.
package login;
import java.io.IOException;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class Login {
private final static String CONSUMER_KEY = "******";
private final static String CONSUMER_KEY_SECRET =
"******";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
// here's the difference
String accessToken = getSavedAccessToken();
String accessTokenSecret = getSavedAccessTokenSecret();
AccessToken oathAccessToken = new AccessToken(accessToken,
accessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
// end of difference
twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");
System.out.println("\nMy Timeline:");
// I'm reading your timeline
ResponseList list = twitter.getHomeTimeline();
/* for (Status each : list) {
System.out.println("Sent by: #" + each.getUser().getScreenName()
+ " - " + each.getUser().getName() + "\n" + each.getText()
+ "\n");
}*/
}
private String getSavedAccessTokenSecret() {
// consider this is method to get your previously saved Access Token
// Secret
return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
}
private String getSavedAccessToken() {
// consider this is method to get your previously saved Access Token
return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
}
public static void main(String[] args) throws Exception {
new Login().start();
}
}
Could I suggest an alternative route..
I have recently been messing around with twitter4j and I approached this slightly differently - I found a nice and easy way to authenticate the client using a ConfigurationBuilder object and passing this to the factory that is getting the instance of the Twitter object you need.
package main;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Base {
protected Twitter twitter;
//protected TwitterStream twitterStream;
private ConfigurationBuilder configBuilder;
public Base(){
configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true);
configBuilder.setOAuthConsumerKey("[consumer key here]");
configBuilder.setOAuthConsumerSecret("[consumer secret key here]");
configBuilder.setOAuthAccessToken("[OAuthAccessToken here]");
configBuilder.setOAuthAccessTokenSecret("[secret OAuthAccessToken here]");
//use the ConfigBuilder.build() method and pass the result to the TwitterFactory
TwitterFactory tf = new TwitterFactory(configBuilder.build());
//you can now get authenticated instance of Twitter object.
twitter = tf.getInstance();
}
}
You could then extend this class with sub classes that implement the functionality you require or just create the ConfigurationBuilder/TwitterFactory/Twitter objects elsewhere in your code.
Below I have implemented a class that creates status' and can return the Status object that holds additional information such as createdAt() and the ID etc etc.
package main;
import twitter4j.Status;
import twitter4j.TwitterException;
public class StatusUpdater extends Base{
public StatusUpdater(){}
public Status updateStatus(String statusToUpdate) throws TwitterException{
Status status = twitter.updateStatus(statusToUpdate);
System.out.println("statusToUpdate: " + status + ".");
return status;
}
}
Then you can use the following statement to create the status. This can be done from mbean/ejb/servlet etc.
try {
StatusUpdater statusUpdater = new StatusUpdater();
String statusTextToSet = "test status";
Status updatedStatus = statusUpdater.updateStatus(statusTextToSet);
System.out.println("Created at: " + updatedStatus.getCreatedAt());
} catch (TwitterException tex) {
System.out.println(tex.getErrorMessage());
}
More info on the configuration process here
Your code looks ok. Have you confirmed your definitely using the correct consumer key and secret for your app? Try twitter.verifyCredentials() to see if you get the same error, or a more specific error.
If you're correcting to the net via a proxy, you will need to include your proxy settings to allow the connection to succeed, details can be found here http://twitter4j.org/en/configuration.html#HTTP%20proxy%20server
As an aside, you may want to remove you access token and secret from your post, if they're still valid then someone could login to your account with them.