Below i have three table which is used for GroupChat,Firstly I am creating the group its all data wil be inserted into GroupTable,then on success of groupCreation i am calling insertConnectionId function which will call the MapGroupConnectionId on backend which generate the SignalR connection ID and insert into GroupTable using groupId and groupCreaterId, its working fine and i have Group Friends Table which consist of Friends ID,Now when any friend sent message to particular Group, i need to send the Message to all who are in that Particular Group through SignalR, i thought, i ll assign the groupConnectionID in group table to all the Members who are related to that Group then i can send message to that particular group which will be received by GroupFriends,My hub which works only for Hub.Client.ALL but not for other function, please guide me if i am doing it in wrong way,I am new to signalR
//Group Table
groupID groupName groupImage groupCreaterId groupConnectionId groupsignalrIsConnected
1 dude someurl 421 somestringID TRUE
2 god someurl 444 somestringID TRUE
3 heaven someurl 543 Null FALSE
4 hell someurl 678 Null FALSE
//Group Friends Table
groupFriendsTabID groupId groupFriendsId
111 2 444
112 3 678
113 2 421
114 4 444
115 1 543
116 4 421
117 1 678
118 2 543
119 3 444
//Group Message Table
groupMesTabId groupId groupsenderId groupMessage
22 1 543 hello
23 3 678 hi
//My HUB
[HubName("groupChatHub")]
public class GroupChatHub : Hub
{
GroupRepository group= new GroupRepository ();
public void **MapGroupConnectionId**(long groupID,int groupCreatorId)
{
if (groupID != 0 && groupCreatorId!=0)
{
CBG.MapGroupConnectionId(groupID, Context.ConnectionId);
Clients.Client(Context.ConnectionId).configureUserSettings();}
}
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
var connectionId = Context.ConnectionId;
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
}
//My WEBAPI//
public class GroupController : ApiControllerWithHub<GroupchatHub>
{
public IhttpActionResult InsertNewMessage(messageModel model)
{
//Here i am inserting new message to Database using some function it works fine//
after success of inserting message i need to send that message to groupmembers using signalr
//here i am fetching the connectionID through groupID from group table
var connectionID=repository.getConnection(model.groupID)
var messager = "11";
Hub.Clients.All.getGroupChat(messager); // this works
Hub.Clients.clients(connectionID).getGroupChat(messager);this not working it except IList<string>
Hub.Clients.Groups(groupName,ConnectionID).getGroupChat(messager); this is not working
}
return ok(Model);
}
//MyClientEnd//
var Grouphub
//this insertConnectionId is called once the group is created on the success of group creation and SignalRconnectionstring is inserted in GroupTable
function insertConnectionId(groupId,groupCreatorID)
$.connection.hub.start().done(function () {
console.log('Now connected, connection ID=' + $.connection.hub.id);
console.log("Connected, transport = " + $.connection.hub.transport.name);
Grouphub.server.mapGroupConnectionId(groupID, groupCreatorID);
});
$.connection.hub.error(function (error) {
console.log('SignalR error: ' + error)
});
});
Grouphub = $.connection.groupChatHub
Grouphub.client.getGroupChat = function (data) {
alert("in");
}
I have done a similar project like and used it in different areas,
Check out this example it will help you :)
https://github.com/DenizGokce/SignalR
Related
I have a custom AX service operation that can take 5+ minutes to complete and I'm trying to figure out how to abort it from my .NET application, but aborting the client doesn't seem to do anything?
The problem is if I call the operation and the service times out, the AX operation continues on until completion, so I lose visibility to the results (success/failure). An example being a long-running posting operation where I don't know if it posted successfully or not.
I've created a simple demo app where I can't seem to get the operation to abort. In the below code I just create a transaction (ttsbegin/ttscommit), insert into a table at start, sleep, insert into table at end.
Sample AX X++ Service Code:
[SysEntryPointAttribute(true)]
public str callAXTimeDelay(int _sleepSeconds)
{
Table1 table1;
ttsBegin;
table1.clear();
table1.SleepData = strFmt("STARTED: %1", DateTimeUtil::utcNow());
table1.insert();
ttsCommit;
sleep(_sleepSeconds * 1000);
ttsBegin;
table1.clear();
table1.SleepData = strFmt("COMPLETED: %1", DateTimeUtil::utcNow());
table1.insert();
ttsCommit;
return strFmt("COMPLETED: %1", DateTimeUtil::utcNow());
}
Then when I call it from .NET, the abort doesn't seem to work? Start/Complete records are still inserted into table1 even though the abort is called before the 15 seconds have completed?
Sample .NET code:
internal class Program
{
static void Main(string[] args)
{
new Program().Run();
Console.WriteLine("Ended, press any key to exit...");
Console.ReadKey();
}
public void Run()
{
AXServicesClient axClient15Sec = new AXServicesClient();
AXServicesClient axClient5sec = new AXServicesClient();
var job15sec = DoLongRunningCall(axClient15Sec, 15);
var job5sec = DoLongRunningCall(axClient5sec, 5);
try
{
var result = Task.Run(() => Task.WhenAny(job15sec, job5sec)).GetAwaiter().GetResult();
if (result == job15sec)
{
Console.WriteLine("job15sec finished first, aborting job5sec");
axClient5sec.Abort();
}
else if (result == job5sec)
{
// This code gets executed because the 5 second job completed and
// it tries to cancel the 15-sec job, but the table ends up with data!
Console.WriteLine("job5sec finished first, aborting job15sec");
axClient15Sec.Abort();
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
axClient15Sec.Abort();
axClient5sec.Abort();
}
axClient15Sec.Close();
axClient5sec.Close();
}
public async Task<string> DoLongRunningCall(AXServicesClient client, int seconds)
{
var result = await client.callAXTimeDelay(new CallContext
{
Company = "ABCD",
Language = "en-us"
}, seconds);
return result.response;
}
}
what changes should I do to the following code to get the following output:
Task 1 complete
Task 4 complete
Task 2 complete
Task 3 complete with task 2 data
I currently getting the outputs given below:
Task 1 complete
Task 2 complete
Task 3 complete with task 2 data
Task 4 complete
import 'dart:async';
void main() {
performTasks();
}
void performTasks() async {
task1();
String task2Result = await task2();
task3(task2Result);
task4();
}
void task1() {
String result = 'task 1 data';
print('Task 1 complete');
}
Future<String> task2() async {
Duration threeSeconds = Duration(seconds: 3);
String result;
await Future.delayed(threeSeconds, () {
result = 'task 2 data';
print('Task 2 complete');
});
return result;
}
void task3(String task2Data) {
String result = 'task 3 data';
print('Task 3 complete with $task2Data');
}
void task4() {
String result = 'task 4 data';
print('Task 4 complete');
}
Don't call task4 after waiting for task2.
So:
void performTasks() async {
task1();
task4();
String task2Result = await task2();
task3(task2Result);
}
That looks pretty obvious, so I'm assuming your real problem is more complicated, and you can't move test4() around like that.
In that case, you should not use await. The await ensures that everything written after the await also executes after the awaited future has completed.
Instead you can fall back on the Future API:
void performTasks() { // no `async`
task1();
task2().then(task3); // no `await`
task4();
}
This sets up task2() to run, and when that is done, it calls task3 with the result. It doesn't wait for anything, though, and it executes task4 immediately after setting this up.
The then method on futures takes a callback, and eventually calls that with the result of the future. Here task3 takes one argument, so it can directly be used as that callback.
That assumes that task2's result is directly usable as an argument to task3. If not, and you have to capture the result and manipulate it first, you'd do it as:
void performTasks() { // no `async`
task1();
task2().then((result2) { // still no await here!
var argument3 = manipulate(result2);
// ... and whatever else you want to do
// between task2 completing and task3 starting.
task3(argument3);
});
task4();
}
in performTasks(), you should move task4(); right after task1();.
In the firestore I created a field named PararUm, type number (it does not have Int, when I enter it manually) and I put value 1.
The problem is that the return has been PararUm(PararUm=1) and not just 1.
(99-below)
When I resolved this, I would have solved the first part of the project.
Regarding the second, I want to use kotlinx.coroutines to work within a while/loop (which queries the value of the PararUm field) in a synchronous, non-asynchronous way (as firebase requires)
Can I do something like???(999-below):
I threw this topic down, but I was not happy1.
99-below:
model
#IgnoreExtraProperties
data class PararUm(
var PararUm: Int? = 0
)
Activity
var db = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var pararumRef =
db.collection("smartmodel").document("xxxxxxxxxxxx")
pararumRef.get().addOnSuccessListener { documentSnapshot ->
var PararUm = documentSnapshot.toObject(PararUm::class.java)
Log.i(ContentValues.TAG, "1999 1999 1999" + PararUm)
}
}
999-below:
while (!FCMotorUmA.value) {
var snapshot = pararumRef.get().await()
var pararum = snapshot.toObject(PararUM::class.java)
if (pararum.equals(0)) {
// Do something 1
} else if (pararum.equals(1)) {
// Do something 2
}
}
Requirement here is I wants to add number of customers on dwolla in one shot. By running dwolla create customer in loop. But things is some customer addition is failing with error,
Error: {“code”:“ServerError”,“message”:“A server error occurred. Error ID: 6188070b-8a1b-4d94-90a5-eb1333d3cd9e.”}
Code:
const client = new dwolla.Client({
key : dwollaCredentials.appKey,
secret : dwollaCredentials.appSecret,
environment : 'sandbox' // optional - defaults to production
});
client.auth.client().then(Meteor.bindEnvironment(function(appToken) {
var spaceProviders = getListofSpaceProvidersWithNoDwollaAcc();
console.log(spaceProviders.length);
for (var i = 0 ; i<spaceProviders.length ; i++) {
var spaceProviderId = spaceProviders[i].id;
var routingNumberUser = spaceProviders[i].routingNo;
var accountNumberUser = spaceProviders[i].accountNumber;
var bankName = spaceProviders[i].firstName+' '+spaceProviders[i].lastName+' Bank';
if (spaceProviders[i]) {
var requestBody = {
firstName : spaceProviders[i].firstName,
lastName : spaceProviders[i].lastName,
email : spaceProviders[i].email
};
console.log('requestBody: ',requestBody);
appToken
.post('customers', requestBody)
.then((res)=> {
var dwollaLocation = res.headers.get('location');
return Promise.resolve(dwollaLocation);
})
.then(Meteor.bindEnvironment((dloc) => {
console.log("dloc"+i+' '+dloc);
return Promise.resolve(dloc);
}))
.catch(error => console.log("Handled Exceptions user",i+' - '+error));
}
}//i
})
);
Somehow bulk customers account creation is failing, may be this is creating continues calls at dwolla and it is unable to handle this much big number, may be one request starts processing and another one is reaching like wise, so finally I am settling for individual "ADD" button for each customer and calling create dwolla customer api on click event.
Help! I've been trying to write a function that will confirm a user's membership in an Active Directory group, and while it works if the member happens to be in the group, it throws an exception if the user is not.
Here is the function:
private bool IsUserMemberOfGroup(string user, string group)
{
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, group))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, user))
{
if (groupPrincipal == null)
{
return false;
}
else
{
return userPrincipal.IsMemberOf(groupPrincipal);
}
}
}
And here is the YSOD:
Server Error in '/' Application.
Unknown error (0x80005000)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Runtime.InteropServices.COMException: Unknown error (0x80005000)
Source Error:
Line 34: else
Line 35: {
Line 36: return userPrincipal.IsMemberOf(groupPrincipal);
Line 37: }
Line 38: }
I don't know if it's related, but when I step through the function, groupPrincipal.Members.Count throws an exception of type "System.NullReferenceException", with Count.Base shows an exception with the message "Object reference not set to instance of an object".
What the heck's going on? Why won't a bool named IsMemberOf just return false when someone's not a member?
Thanks,
Daniel
I think you could simplify things a bit:
private bool IsUserMemberOfGroup(string user, string group)
{
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, user))
{
PrincipalSearchResult<Principal> result = userPrincipal.GetGroups();
GroupPrincipal groupPrincipal =
result.Where(g => g.SamAccountName == groupName).FirstOrDefault();
return (groupPrincipal != null);
}
}
The userPrincipal.GetGroups() will give you a definitive list of all group memberships (including primary group and nested group memberships) for that user; then search that list for the group you're interested in, e.g. by samACcountName or some other property.
If you find the group you're looking for in the PrincipalSearchResult<Principal> returned by GetGroups(), then your user is a member of that group.
You can save yourself at least one "FindByIdentity" call with this.
A minor modification top the code from marc_s, I have:
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, user))
using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, group))
{
if (userPrincipal == null) return false;
if (groupPrincipal == null) return false;
PrincipalSearchResult<Principal> result = userPrincipal.GetGroups();
Principal grp = result.Where(g => g.Sid == groupPrincipal.Sid).FirstOrDefault();
return (grp != null);
}
Comparing Sid seems to work more reliably than comparing SamAccountName.
We had a bit of a poison group in our setup which caused this to fail for some users but not others. The "FirstOrDefault" logic in the other suggested answers MIGHT have helped us dodge the poison group, but that is no guarantee.
We have two suggestions for others with this problem. First check if you have any groups with a forward slash in the group name (the actual group name, not the "pre-windows 2000" name which will replace it with an underscore). If you can rename all such groups that might fix your problem ... it worked for us.
This workaround also was working for us:
/// <summary>
/// This does a recursive group search for the given user or computer principal.
/// </summary>
public IEnumerable<Principal> GetGroups(Principal principal)
{
return GetGroups(null, principal);
}
private IEnumerable<Principal> GetGroups(HashSet<SecurityIdentifier> ancestorPrincipalSids, Principal parentPrincipal)
{
try
{
//enumerate this here so errors are thrown now and not later
//if the current group name has a forward-slash, I think this
//will always error here
var groups = parentPrincipal.GetGroups().ToArray();
if (groups == null)
{
return Enumerable.Empty<Principal>();
}
//keep track of all ancestors in the group hierarchy to this point
//so that we can handle circular references below
var newAncestors = new HashSet<SecurityIdentifier>(ancestorPrincipalSids ?? Enumerable.Empty<SecurityIdentifier>());
newAncestors.Add(parentPrincipal.Sid);
return groups
.Concat(groups
.Where(g => !newAncestors.Contains(g.Sid)) //handle circular references
.SelectMany(g => GetGroups(newAncestors, g)));
}
catch
{
return Enumerable.Empty<Principal>();
}
}