Adding an event based on logged user


#1

Hi everyone!

I’m using dhtmlxScheduler on ASP.NET Web Applications with Web Forms. I have created the events table, and the events are added just fine, but I want to create a condition. In my app you can log in with an account. I save this account infos in an Users table. What I want to do is to add an avent based on the logged in user. When the user is logging in, i’m saving his ID in a Session variable as below:
Session[“UserID”] = dt.Rows[0][“Id”];

What i’m asking you is where i should make changes to add the event based on the logged in user? I don’t know in which file i should look.

Thank you!


#2

Hi @Melissa!

can you show a general structure of your project, to give me a better idea of how it’s configured on your end? A screenshot from the Solution Explorer would do, it’s just for the general understanding of your app.

Do you use dhtmlxScheduler for .NET - https://www.nuget.org/packages/DHTMLX.Scheduler.NET/
or do you use the javascript version of the scheduler https://docs.dhtmlx.com/scheduler/server_integration.html and implement the backend manually?

Also, can you please clarify what exactly do you mean by adding an event based on the logged user?

Do you mean you add a user id to every event, e.g. event.userID = Session["UserID"], or do you mean something else?


#3

Hi @Aliaksandr !
I’m using the library from Nuget in asp.net.
So my app is something like this: the user is logging in, and i’m saving his id in a Session variable (Session[“UserID”]. He has some functionalities in this one, and one of them is this dhtmlx Scheduler, where the user adds some new events. This Events are saved in a table in my Database.
What I wanna basically do is to show to the user A, let’s say, only the events added by him, not the events added by user B. That’s the code for my Evets table:
CREATE TABLE [dbo].[Events] (
[id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (256) NULL,
[start_date] DATETIME NOT NULL,
[end_date] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([id] ASC)
);

What I want to do is to add a new column in this table, let’s say UserID, which should be a foreign key to the table where I’m saving my users.
The problem is that I don’t know where in the generated files by the DHTMLX Scheduler I can find the query that selects this events from my table. I have a Schedule.dbml that looks like this, but I don’t thinks that this is the right place to make my changes:

<?xml version="1.0" encoding="utf-8"?>

Also I have a file named Data.ashx.cs where I have this function which is extracting my events I guess

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = “text/json”;// the data comes in JSON format
context.Response.Write(
new SchedulerAjaxData(new SchedulerDataContext().Events) //events for loading to scheduler
);
}

And I have this class in which I save my data

public class Save : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/xml";// the data is passed in XML format

        var action = new DataAction(context.Request.Form);
        var data = new SchedulerDataContext();

        try
        {
            var changedEvent = (Event)DHXEventsHelper.Bind(typeof(Event), context.Request.Form);//see details below

            switch (action.Type)
            {
                case DataActionTypes.Insert: // your Insert logic
                    data.Events.InsertOnSubmit(changedEvent);
                    break;
                case DataActionTypes.Delete: // your Delete logic
                    changedEvent = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                    data.Events.DeleteOnSubmit(changedEvent);
                    break;
                default:// "update" // your Update logic
                    var updated = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                    DHXEventsHelper.Update(updated, changedEvent, new List<string>() { "id" });// see details below
                    break;
            }
            data.SubmitChanges();
            action.TargetId = changedEvent.id;
        }
        catch (Exception a)
        {
            action.Type = DataActionTypes.Error;
        }

        context.Response.Write(new AjaxSaveResponse(action));
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Maybe you can understand now better what I want to do. I just basically want to change in some way the code to save my session variable in the Events table and show in my Scheduler only the events added by the logged in user.

Thank you for your time! :slight_smile:


#6

Hi,

dbml files are a part of LinqToSql database binding, and they are generated from the database tables (like DatabaseFirst approach in Entity Framework).

I would advise against modifying xml files directly, it will be much simpler to update them from the database using visual tools.
So in order to add a new column to the model, you first need to add it to the database table and then re-generate dbml models, it’s done in the visual editor by dragging tables from the Server Explorer into the designer area.
Modern versions of VisualStudio doesn’t include the visual designer tool, so you’ll have to install it manually https://superuser.com/questions/1193196/how-to-open-dbml-in-designer-mode-with-vs
https://stackoverflow.com/questions/1110171/how-do-i-update-a-linq-to-sql-dbml-file

However, since LinqToSql looks abandoned nowadays, I’d recommend rewriting the data access using EntityFramework. It won’t require much code changes
http://scheduler-net.com/docs/tutorialsentity-framework-code-first.html

Once you have the model with all the required properties, you’ll be able to filter events by user id in the data.ashx:

select events created by the current user:

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";// the data comes in JSON format
context.Response.Write(
new SchedulerAjaxData(new SchedulerDataContext().Events.Where(e => e.userId == Session["UserID"]) //events for loading to scheduler
);
}

save.ashx - add userId to new events, ensure users can’t delete or modify events created by other users

public class Save : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/xml";// the data is passed in XML format

        var action = new DataAction(context.Request.Form);
        var data = new SchedulerDataContext(); //EntityFramework Context

        try
        {
            var changedEvent = (Event)DHXEventsHelper.Bind(typeof(Event), context.Request.Form);//see details below

            switch (action.Type)
            {
                case DataActionTypes.Insert: // your Insert logic
// !!!
                    changedEvent.userId = Session["UserID"];// !!!

                    data.Events.Add(changedEvent);
                    break;
                case DataActionTypes.Delete: // your Delete logic


                    changedEvent = data.Events.FirstOrDefault(ev => ev.id == action.SourceId);
// !!!
                    if(changedEvent.userId == Session["UserID"]){
                       throw new Exception("You can delete your events only")
                    }

                    data.Events.Remove(changedEvent);

 
                    break;
                default:// "update" // your Update logic
// !!!
                    if(changedEvent.userId == Session["UserID"]){
                       throw new Exception("You can edit your events only")
                    }
                    var target = data.Events.Single(e => e.id == changedEvent.id);
                    DHXEventsHelper.Update(target, changedEvent, new List<string> { "id" });
                    break;
                }
                entities.SaveChanges();
                action.TargetId = changedEvent.id;
        }
        catch (Exception a)
        {
            action.Type = DataActionTypes.Error;
        }

        context.Response.Write(new AjaxSaveResponse(action));
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

please note that I didn’t test the code above, it’s here just to illustrate the approach


#7

@Aliaksandr ok so I will try to implement this code. If it works as I expect ( and just by looking at the code you gave me I think it should work ), I am really in your debt :smile:

Thank you so so much for this! :hugs: