Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            SetLoggerSettings("App.config");
            logger.Info("Start");

            Session session = null;
            IDoc    app     = null;

            //Result exception in TryConvert.
            try
            {
                var config = new EnigmaConfigurations()
                {
                    Url = $"ws://127.0.0.1:4848/app/engineData/identity/{Guid.NewGuid()}",
                    //Url = $"wss://127.0.0.1/app/engineData/identity/{Guid.NewGuid()}",

                    // if you want to create your own Connection with for example header / cookies, just inject this in line
                    CreateSocket = async(url) =>
                    {
                        var ws = new ClientWebSocket();
#if NETCOREAPP2_1
                        var ck = new CookieContainer();
                        ck.Add(new Uri(url), new Cookie("X-Qlik-Session", "xxxxxxxxx"));
                        ws.Options.Cookies = ck;
                        ws.Options.RemoteCertificateValidationCallback
                            += new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(true); });
#endif
                        //!!!!!!!!!here you can inject your cookie, header authentification,...
                        await ws.ConnectAsync(new Uri(url), CancellationToken.None);

                        return(ws);
                    }
                };

                session = Enigma.Create(config);
                // connect to the engine
                var globalTask = session.OpenAsync();
                globalTask.Wait();

                IGlobal global  = Impromptu.ActLike <IGlobal>(globalTask.Result);
                var     appName = SenseUtilities.GetFullAppName("Executive Dashboard");
                app         = global.OpenDocAsync(appName).Result;
                app.Closed += App_Closed;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            var mytasks = new List <Task>();
            var ce1     = new CalculationExample(app);

            ce1.CalcRandom(120);

            Task.WaitAll(mytasks.ToArray());

            var count = mytasks.Count;

            //global.EngineVersionAsync()
            //    .ContinueWith((engVer) =>
            //    {
            //        Console.WriteLine("CastedEngineVer:" + engVer.Result.qComponentVersion);
            //    });

            //global.OpenDocAsync(appName)
            //    .ContinueWith((newApp) =>
            //    {

            //        Console.WriteLine("Object " + (newApp.Result).ToString());

            //        var app = newApp.Result;

            //        // test the changed notification of the opend app
            //        app.Changed += App_Changed;

            //        // just a normal get script
            //        app.GetScriptAsync()
            //            .ContinueWith((script) =>
            //            {
            //                Console.WriteLine("Script" + script.Result.ToString().Substring(1, 100));
            //            });

            //        // change the script, so that the app changed is triggered
            //        app.SetScriptAsync("HALLO")
            //            .ContinueWith((res) =>
            //            {
            //                // read the changed script
            //                app.GetScriptAsync()
            //                    .ContinueWith((script) =>
            //                    {
            //                        Console.WriteLine("Script2" + script.Result.ToString());
            //                    });
            //            });

            //    });

            //Thread.Sleep(3000);
            var example = new ChangeEventsExample(app);

            example.RunExample();

            var tasks = new List <Task>();
            //Set bookmark test
            var bookmark = app.GetBookmarkAsync("demobookmark").Result;

            //evaluate request
            var request = JObject.FromObject(new
            {
                qExpression = "'$(vCurrentYear)'"
            });

            //Use this Overload from EvaluateExAsync it works fine.
            var result = app.EvaluateExAsync(request).Result;

            //Use this Overload it crashes!!!
            result = app.EvaluateExAsync("'$(vCurrentYear)'").Result;

            //Caluculation Test
            var calc = new CalculationExample(app);

            calc.CalcRandom(1);

            //find the bookmark with type
            var bookmarkExample = new BookmarkExample(app);

            tasks.Add(bookmarkExample.ListBookmarksAsync());

            //find dimensions
            var dimensionExample = new DimensionExample(app);

            tasks.Add(dimensionExample.ListDimensionsAsync());

            //find current selections
            var selectionExample = new SelectionExample(app);

            tasks.Add(selectionExample.ListCurrentSelectionsAsync());

            ////find list object data
            var listObjectExample = new ListObjectExample(app);

            tasks.Add(listObjectExample.ListListObjectDataAsync());

            ////Fire Multiple Requests
            var multipleRequestsExample = new MultipleRequests(app);

            tasks.Add(multipleRequestsExample.FireMultipleRequestsAsync());

            Task.WaitAll(tasks.ToArray());

            var task5 = listObjectExample.GetGenericObjectAsync("Region");

            var task6 = listObjectExample.GetListObjectDataAsync(task5.Result);

            dynamic jsonObject = task6.Result;

            foreach (var item in jsonObject[0].qMatrix)
            {
                Console.WriteLine(item[0]?.qText + "");
            }

            Console.WriteLine("Finish");
            var _ = session.CloseAsync();

            Console.ReadLine();
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting...");
            Console.WriteLine("Read Settings...");

            var content  = File.ReadAllText("settings.json");
            var settings = JsonConvert.DeserializeObject <Settings>(content);

            Session session = null;
            IDoc    app     = null;

            try
            {
                var config = new EnigmaConfigurations()
                {
                    Url          = settings.ServerUri.AbsoluteUri,
                    CreateSocket = async(url) =>
                    {
                        var ws = new ClientWebSocket();
                        await ws.ConnectAsync(new Uri(url), CancellationToken.None);

                        return(ws);
                    }
                };

                session = Enigma.Create(config);
                var globalTask = session.OpenAsync();
                globalTask.Wait();
                IGlobal global  = Impromptu.ActLike <IGlobal>(globalTask.Result);
                var     appName = settings.App;
                Console.WriteLine($"Connect to App {appName}...");
                app = global.OpenDocAsync(appName).Result;

                Console.WriteLine($"Create Connections...");
                foreach (var qconn in settings.Connections)
                {
                    try
                    {
                        var connConfig = new Connection()
                        {
                            qType             = qconn.Type,
                            qName             = qconn.Name,
                            qConnectionString = qconn.ConnectionString
                        };
                        Console.WriteLine($"Create connection...");
                        var test = app.CreateConnectionAsync(connConfig).Result;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"No Connection created: {ex.ToString()}");
                    }
                }

                foreach (var scriptPath in settings.Scripts)
                {
                    var scriptContent = File.ReadAllText(scriptPath);
                    Console.WriteLine($"Reload Script...");
                    app.SetScriptAsync(scriptContent).Wait();
                    app.DoReloadAsync().Wait();
                }

                Console.WriteLine($"Finish.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error:\n{ex.ToString()}");
                Console.ReadLine();
            }
        }
Ejemplo n.º 3
0
        public bool Connect(bool loadPossibleApps = false)
        {
            try
            {
                logger.Info($"Connect to: {ConnectUri.AbsoluteUri}");
                var config = new EnigmaConfigurations()
                {
                    Url          = ConnectUri.AbsoluteUri,
                    CreateSocket = async(Url) =>
                    {
                        var webSocket = new ClientWebSocket();
                        webSocket.Options.Cookies = new CookieContainer();
                        webSocket.Options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                        var credentials = Config?.Credentials ?? null;
                        var credType    = Config?.Credentials?.Type ?? QlikCredentialType.NONE;
                        logger.Debug($"Connection type is '{credType}'");
                        var jwtSession = new JwtSessionManager();
                        switch (credType)
                        {
                        case QlikCredentialType.SESSION:
                            logger.Debug($"Session-Cookie {credentials?.Key}={credentials?.Value}.");
                            ConnectCookie = new Cookie(credentials?.Key, credentials?.Value)
                            {
                                Secure = true,
                                Domain = ConnectUri.Host,
                                Path   = "/",
                            };
                            webSocket.Options.Cookies.Add(ConnectCookie);
                            logger.Debug($"Session type: {credentials?.Type} with Session {credentials?.Value}");
                            break;

                        case QlikCredentialType.JWT:
                            logger.Debug($"Jwt type: {credentials?.Key} - {credentials?.Value}.");
                            var newCookie = jwtSession.GetJWTSession(Config.ServerUri, credentials?.Value.Replace("Bearer ", ""), "X-Qlik-Session-ser");
                            ConnectCookie = newCookie;
                            webSocket.Options.Cookies.Add(ConnectCookie);
                            break;

                        case QlikCredentialType.CLOUD:
                            logger.Debug($"Connecting to Qlik Cloud.");
                            logger.Debug($"Cloud type: {credentials?.Key} - {credentials?.Value}.");
                            webSocket.Options.SetRequestHeader(credentials?.Key, credentials?.Value);
                            break;

                        case QlikCredentialType.NEWSESSION:
                            logger.Debug($"Connecting to Qlik with a new Session.");
                            logger.Debug($"Session infos: {credentials?.Key} - {credentials?.Value}.");
                            var newSession = jwtSession.CreateNewSession(Config, new DomainUser(credentials?.Value), Config.App);
                            ConnectCookie = newSession.Cookie;
                            webSocket.Options.Cookies.Add(ConnectCookie);
                            break;

                        case QlikCredentialType.NONE:
                            // No Authentication for DESKTOP and DOCKER
                            logger.Debug($"None type: No Authentication.");
                            break;

                        default:
                            throw new Exception("Unknown Qlik connection type.");
                        }
                        webSocket.Options.KeepAliveInterval = TimeSpan.FromDays(48);
                        await webSocket.ConnectAsync(new Uri(Url), CancellationToken.None);

                        return(webSocket);
                    },
                };

                SocketSession = Enigma.Create(config);
                var globalTask = SocketSession.OpenAsync();
                globalTask.Wait(7500);
                if (!globalTask.IsCompleted)
                {
                    throw new Exception("No connection to qlik.");
                }
                IGlobal global = Impromptu.ActLike <IGlobal>(globalTask.Result);
                var     task   = global.IsDesktopModeAsync();
                task.Wait(2500);
                if (!task.IsCompleted)
                {
                    throw new Exception("No connection to qlik.");
                }
                if (task.Result)
                {
                    Mode = QlikAppMode.DESKTOP;
                }
                if (loadPossibleApps)
                {
                    lock (lockObject)
                    {
                        PossibleApps = global.GetDocListAsync().Result;
                    }
                }
                logger.Debug($"Use connection mode: {Mode}");
                if (IsSharedSession)
                {
                    try
                    {
                        CurrentApp = global.GetActiveDocAsync().Result;
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, "No existing shared session found. Please open the app in the browser.");
                        return(false);
                    }
                }
                else
                {
                    var appName = String.Empty;
                    if (Mode == QlikAppMode.DESKTOP)
                    {
                        appName = HelperUtilities.GetFullAppName(Config.App);
                    }
                    else
                    {
                        appName = GetAppId(global);
                    }
                    logger.Debug($"Connect with app name: {appName}");
                    CurrentApp = global.OpenDocAsync(appName).Result;
                }
                logger.Debug("The Connection to Qlik was successfully");
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"The connection to Qlik Sense with uri '{ConnectUri}' app '{Config.App}' could not be established.");
                return(false);
            }
        }
Ejemplo n.º 4
0
        public IGlobal GetGlobelContext()
        {
            try
            {
                logger.Debug("Create global context");
                var config = new EnigmaConfigurations()
                {
                    Url          = ConnectUri.AbsoluteUri,
                    CreateSocket = async(Url) =>
                    {
                        var webSocket = new ClientWebSocket();
                        webSocket.Options.Cookies = new CookieContainer();

                        var callback = ServicePointManager.ServerCertificateValidationCallback;
                        if (callback == null)
                        {
                            throw new NotImplementedException(".NET has no certificate check");
                        }

                        var credentials = Config?.Credentials ?? null;
                        var credType    = Config?.Credentials?.Type ?? QlikCredentialType.NONE;
                        switch (credType)
                        {
                        case QlikCredentialType.CERTIFICATE:
                            var domainUser = new DomainUser(credentials.Value);
                            var options    = new CookieConnectionOptions()
                            {
                                CertificatePath = credentials?.Cert ?? null,
                                HeaderName      = "X-Qlik-User",
                                HeaderValue     = $"UserDirectory={domainUser.UserDirectory};UserId={domainUser.UserId}",
                                UseCertificate  = true,
                            };

                            var qlikClientCert = new X509Certificate2();
                            qlikClientCert = qlikClientCert.GetQlikClientCertificate(options.CertificatePath);
                            webSocket.Options.ClientCertificates.Add(qlikClientCert);
                            webSocket.Options.SetRequestHeader(options.HeaderName, options.HeaderValue);
                            logger.Debug($"Credential type: {credentials?.Type}");
                            break;

                        case QlikCredentialType.WINDOWSAUTH:
                            webSocket.Options.Credentials = new NetworkCredential(credentials?.Key, credentials?.Value);
                            logger.Debug($"WinAuth type: {credentials?.Type} with User {credentials?.Key}");
                            break;

                        case QlikCredentialType.SESSION:
                            logger.Debug($"Session-Cookie {credentials?.Key}={credentials?.Value}.");
                            ConnectCookie = new Cookie(credentials?.Key, credentials?.Value)
                            {
                                Secure = true,
                                Domain = ConnectUri.Host,
                                Path   = "/",
                            };
                            webSocket.Options.Cookies.Add(ConnectCookie);
                            logger.Debug($"Session type: {credentials?.Type} with Session {credentials?.Value}");
                            break;

                        case QlikCredentialType.NONE:
                            logger.Debug($"None type: No Authentication.");
                            // No Authentication for DESKTOP and DOCKER
                            break;

                        default:
                            throw new Exception("Unknown Qlik connection type.");
                        }
                        webSocket.Options.KeepAliveInterval = TimeSpan.FromDays(48);
                        await webSocket.ConnectAsync(new Uri(Url), CancellationToken.None);

                        return(webSocket);
                    },
                };

                SocketSession = Enigma.Create(config);
                var globalTask = SocketSession.OpenAsync();
                globalTask.Wait();
                logger.Debug("Found globel context");
                return(Impromptu.ActLike <IGlobal>(globalTask.Result));
            }
            catch (Exception ex)
            {
                logger.Debug(ex, "No Global context");
                return(null);
            }
        }