Esempio n. 1
0
        public ActionResult Login(string username, string tel)
        {
            bool Success = false;
            userinfo currentModel = Daxu.BLL.userinfoBll.GetEntity<userinfo>(new SearchEntityList()
            {
                ModelEqual = "userinfo",
                TellEqual = tel,
                userNameEqual = username

            }, null);
            if (currentModel != null)
            {

                WebContext webcontex = new WebContext(HttpContext);
                webcontex.UserLogin(username, new UserData()
                {
                    UserID = currentModel.id,
                    UserName = currentModel.name,
                    FullName = currentModel.name
                });
                return Json(new ResultMessage() { Success = true, Message = "正在跳转..." });

            }
            else
            {
                return Json(new ResultMessage() { Success = false, Message = "用户信息出错!" });

            }
        }
Esempio n. 2
0
        private static void ListInstrumentsJSON(WebContext context, Song s)
        {
            JSONWriter jw = new JSONWriter();
            jw.Array();

            for (int k = 0; k < s.Instruments.Count; k++)
            {
                Instrument ins = s.Instruments[k];

                jw.Class();
                jw.Field("id", ins.ID);
                jw.Field("name", ins.Name);
                jw.Field("device", ins.MidiDevice);
                jw.Field("channel", ins.MidiChannel);
                jw.Field("patch", ins.MidiPatch);
                jw.Field("type", ins.Type);
                jw.End();
            }

            jw.End();

            context.Response.Write("g_Instruments = ");
            context.Response.Write(jw.ToString(JSONFormatting.Pretty));
            context.Response.Write(";\n");
        }
Esempio n. 3
0
        private void doProcessRequest(HttpContext httpcontext)
        {
            PatcherInfo.instance.CheckDBUpToDate();

            Uri current = httpcontext.Request.Url;
            if(!current.Host.EndsWith(Config.instance.BaseHost)) {
                throw new FLocalException("Wrong host: " + current.Host + " (expected *" + Config.instance.BaseHost + ")");
            }
            if(Config.instance.forceHttps && !httpcontext.Request.IsSecureConnection) {
                throw new FLocalException("Only HTTPS connections are allowed");
            }

            Uri referer = httpcontext.Request.UrlReferrer;
            if(referer != null && referer.PathAndQuery.StartsWith("/static") && !httpcontext.Request.Path.StartsWith("/static")) {
                throw new HttpException(403, "You have come from the static page '" + referer + "'");
            }

            WebContext context = new WebContext(httpcontext);
            try {
                ISpecificHandler handler = HandlersFactory.getHandler(context);
                handler.Handle(context);
            } catch(WrongUrlException) {
                (new handlers.WrongUrlHandler()).Handle(context);
            }
        }
Esempio n. 4
0
 public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) {
     var ctx = RequestParameters.Create(context);
     var login = ctx.Get("login");
     var role = ctx.Get("role");
     var exact = ctx.Get("exact").ToBool();
     if (string.IsNullOrWhiteSpace(role)) {
         context.Finish("{\"error\":\"emptyrole\"}", status: 500);
         return;
     }
     if (string.IsNullOrWhiteSpace(login)) {
         login = context.User.Identity.Name;
     }
     var result = false;
     if (login != context.User.Identity.Name) {
         if (!Roles.IsInRole(context.User.Identity, SecurityConst.ROLE_ADMIN)) {
             context.Finish("{\"error\":\"adminrequire\"}", status: 500);
             return;
         }
         result = Roles.IsInRole(login, role, exact);
     }
     else {
         result = Roles.IsInRole(context.User.Identity, role, exact);
     }
     context.Finish(result.ToString().ToLowerInvariant());
 }
Esempio n. 5
0
 public void LoadDisplay(File file)
 {
     IWebContext _webcontext = new WebContext();
     UserSession _usersession = new UserSession();
     if (_usersession.CurrentUser != null)
     {
         if (_webcontext.AccountID > 0 && _usersession.CurrentUser.AccountID != _webcontext.AccountID)
         {
             if (file.IsPublicResource == true)
             {
                 Image1.ImageUrl = "~/Photo/ProfileAvatar.aspx?FileID=" + file.FileID;
                 Name.Text = file.FileName;
                 Date.Text = file.CreateDate.ToString();
                 Desc.Text = "File Share by"+ file.AccountID;
                 FileID.Text = file.FileID.ToString();
                 Ispublic.Checked = true;
                 LoadFriend();
             }
             else div1.Visible = false;
         }
         else
         {
             Image1.ImageUrl = "~/Photo/ProfileAvatar.aspx?FileID=" + file.FileID;
             Name.Text = file.FileName;
             Date.Text = file.CreateDate.ToString();
             Desc.Text = "File Share by" + file.AccountID;
             FileID.Text = file.FileID.ToString();
             Ispublic.Checked = file.IsPublicResource;
             LoadFriend();
         }
     }
 }
Esempio n. 6
0
 public bool Login(string Username, string Password, bool rememberMe, out String returnMessage)
 {
     if (rememberMe == false)
         return Login(Username, Password,out returnMessage);
     IWebContext webContext = new WebContext();
     webContext.SaveLoginInfoToCookie(Username, Password);
     return Login(Username, Password, out returnMessage);
 }
Esempio n. 7
0
 static void AuthorizeRequest(object sender, EventArgs e)
 {
     var context = new WebContext(HttpContext.Current);
     foreach (var pipe in Pipeline)
     {
         pipe.Before(context);
     }
 }
Esempio n. 8
0
 public ShowFriendPresenter()
 {
     _friendRepository = new SPKTCore.Core.DataAccess.Impl.FriendRepository();
     _userSession = new SPKTCore.Core.Impl.UserSession();
     _friendService = new FriendService();
     _ac = new SPKTCore.Core.DataAccess.Impl.AccountRepository();
     _webcontext = new WebContext();
 }
Esempio n. 9
0
        //--------------------登录、注销相关方法------------------------------------------------
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="context"></param>
        public void UserLogin( String userName, HttpContext context )
        {
            User user = getUserByName( userName );
            if (user == null) throw new NullReferenceException( "试图登录的用户不存在,用户名=" + user.Name );

            WebContext webContext = new WebContext( context );
            // 注意:传入的Id和wojilu的ID是不同步的
            webContext.UserLogin( user.Id, user.Name, wojilu.Common.LoginTime.OneMonth );
        }
Esempio n. 10
0
        /// <summary>
        /// Creates a new <see cref="App"/> instance.
        /// </summary>
        public App() {
            InitializeComponent();

            // Create a WebContext and add it to the ApplicationLifetimeObjects
            // collection.  This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            //webContext.Authentication = new WindowsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);
        }
Esempio n. 11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            _redirector = new Redirector();
            _usersession = new UserSession();
            _webcontext=new WebContext();
            _fi=new FriendInvitationRepository();
            _ac = new AccountRepository();
            _mr = new MessageRecipientRepository();
            _f = new FriendService();
            Account acid;

            if (_usersession.CurrentUser != null)
            {
                if (_webcontext.AccountID != _usersession.CurrentUser.AccountID && _webcontext.AccountID != 0)
                {
                    acid = _ac.GetAccountByID(_webcontext.AccountID);
                    lblProfileName.Text = acid.UserName;
                    lb_ban.Text = " ( " + _f.SearchFriend(acid).Count.ToString() + " )";
                    testImage.Src = "~/Image/ProfileAvatar.aspx?AccountID=" + acid.AccountID;
                    AccordionPane1.Visible = false;
                    AccordionPane3.Visible = false;
                    id = acid.AccountID;
                    lbtnChangeAvatar.Visible = false;
                }
                else
                {
                    lblProfileName.Text = _usersession.CurrentUser.UserName;
                    lb_ban.Text = " ( " + _f.SearchFriend(_usersession.CurrentUser).Count.ToString() + " )";
                    testImage.Src = "~/Image/ProfileAvatar.aspx?AccountID=" + _usersession.CurrentUser.AccountID;
                    AccordionPane1.Visible = true;
                    AccordionPane3.Visible = true;
                    lb_invite.Text = " ( " + _fi.FriendInv(_usersession.CurrentUser).Count.ToString() + " )";
                    id = _usersession.CurrentUser.AccountID;
                    lb_message.Text = " ( 0 ) ";
                    lbtnChangeAvatar.Visible = true;
                    //lb_message.Text = " ( " + _mr.getMessageRecipientByAccountID(_usersession.CurrentUser.AccountID).Count.ToString() + " ) ";
                }
            }
            else
            {
                if (_webcontext.AccountID > 0)
                {
                    acid = _ac.GetAccountByID(_webcontext.AccountID);
                    lblProfileName.Text = acid.UserName;
                    testImage.Src = "~/Image/ProfileAvatar.aspx?AccountID=" + acid.AccountID;
                    AccordionPane1.Visible = false;
                    AccordionPane3.Visible = false;
                    id = acid.AccountID;
                    lbtnChangeAvatar.Visible = false;
                }
                else
                    _redirector.GoToAccountLoginPage();

            }
        }
Esempio n. 12
0
        /// <summary>
        /// Создает новый экземпляр класса <see cref="App"/>.
        /// </summary>
        public App()
        {
            InitializeComponent();

            // Создание объекта WebContext и добавление его в коллекцию ApplicationLifetimeObjects.
            // После этого он будет доступен как WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            //webContext.Authentication = new WindowsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);
        }
Esempio n. 13
0
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            WebContext webContext = new WebContext();
            this.ApplicationLifetimeObjects.Add(webContext);

            InitializeComponent();
        }
Esempio n. 14
0
        /// <summary>
        /// Creates the web context instance.
        /// </summary>
        internal static void CreateInstance()
        {
            lock (_lock)
            {
                if (_instance != null)
                    throw new InvalidOperationException("WebContext instance already exists.");

                _instance = new WebContext();
                _instance._channelFactory = new ChannelFactory<ITestHostService>(
                    new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/testhost"));
            }
        }
Esempio n. 15
0
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            WebContext context = new WebContext();
            context.Authentication = new FormsAuthentication();
            this.ApplicationLifetimeObjects.Add(context);
        }
Esempio n. 16
0
 protected void Page_Load(object sender, EventArgs e)
 {
     //file1.Visible = false;
     _usersession = new UserSession();
     _webcontext = new WebContext();
     _for = new FolderRepository();
     re = new Redirector();
     if (_usersession.CurrentUser != null)
     {
        countA.Text=(_for.GetFoldersByAccountID1(_usersession.CurrentUser.AccountID)).Count.ToString();
       // pn.Height = 200 * (int.Parse(countA.Text));
     }
 }
Esempio n. 17
0
        /// <summary>
        /// Creates a new <see cref="App"/> instance.
        /// </summary>
        public App()
        {
            InitializeComponent();

            _busyIndicator = new BusyIndicator();
            _busyIndicator.BusyContent = "User Authenticating, Please Wait...";
            // Create a WebContext and add it to the ApplicationLifetimeObjects collection.
            // This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            //webContext.Authentication = new WindowsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);
        }
Esempio n. 18
0
        /// <summary>
        /// Creates a new <see cref="App"/> instance.
        /// </summary>
        public App()
        {
            InitializeComponent();

            // Create a WebContext and add it to the ApplicationLifetimeObjects collection.
            // This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            //webContext.Authentication = new WindowsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);

            //initialize culture
            //Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-IN");
        }
Esempio n. 19
0
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            // 初期化
            var webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);
            MVVMRxSampleApplication.Initialize(webContext);
        }
Esempio n. 20
0
 protected override HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) {
     var result = UserProcessor.DefineUser(context);
     var param = RequestParameters.Create(context);
     return new HandlerResult {
         Result = result,
         Data = new{
             result,
             call = new {
                 q = param.Query,
                 j = param.Json.jsonify()
             }
         }
     };
 }
Esempio n. 21
0
 protected virtual HandlerResult DefaultProcess(IHostServer server, WebContext context, string callbackEndPoint,
     CancellationToken cancel) {
     var result = GetResult(server, context, callbackEndPoint, cancel) ?? HandlerResult.Null;
     var outer = result.Result;
     if (result.Mime == "application/json") {
         var str = outer as string;
         if (null != str &&
             ((str.StartsWith("{") && str.EndsWith("}")) || (str.StartsWith("[") && str.EndsWith("]")))) {
             outer = str.jsonify();
         }
         outer = outer.stringify();
         context.Finish(outer, result.Mime, result.State);
     }
     return result;
 }
Esempio n. 22
0
		public void Constructor_PathWithPortAndQueryString_SetCorrectly()
		{
			// Assign

			_owinContext.SetupGet(x => x.Request.Uri).Returns(new Uri("http://localhost:8080?act=test"));
			_owinContext.SetupGet(x => x.Request.PathBase).Returns(new PathString(""));

			// Act
			var context = new WebContext(_owinContext.Object);

			// Assert

			Assert.AreEqual("http://localhost:8080/", context.SiteUrl);
			Assert.AreEqual("", context.VirtualPath);
		}
Esempio n. 23
0
        /// <summary>
        /// Creates a new <see cref="App"/> instance.
        /// </summary>
        public App()
        {
            InitializeComponent();

            // Create a WebContext and add it to the ApplicationLifetimeObjects collection.
            // This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            //webContext.Authentication = new WindowsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);

            client = new Server.ServiceTcpClient();
            client.Endpoint.Behaviors.Add(new CustomHeaders.ConsumerEndpointBehavior());

        }
Esempio n. 24
0
		public App() {
			this.Startup += this.Application_Startup;
			this.UnhandledException += this.Application_UnhandledException;
			WebContext webcontext = new WebContext();
			webcontext.Authentication = new System.ServiceModel.DomainServices.Client.ApplicationServices.WindowsAuthentication();

			LoggerContext context = new LoggerContext();
			Logging.Logger.init(context);

			this.ApplicationLifetimeObjects.Add(webcontext);
			
			webcontext.Authentication.LoadUser(OnLoadUser_Completed, null);
			
			InitializeComponent();
		}
Esempio n. 25
0
        private void OnWebSocketAccepted(WebContext webContext, Task <WebSocket> task)
        {
            WebSocket webSocket;

            if (MiscHelpers.Try(out webSocket, () => task.Result))
            {
                if (!ConnectClient(webSocket))
                {
                    webSocket.Close(WebSocket.ErrorCode.PolicyViolation, "A debugger is already connected");
                }
            }
            else
            {
                webContext.Response.Close(500);
            }
        }
Esempio n. 26
0
        public override void HandleRequest(WebContext context)
        {
            Console.WriteLine("got request (#" + Thread.CurrentThread.ManagedThreadId + ") for: " + context.Request.LocalPath);
            if (context.Request.LocalPath == "/")
                HandleRootRequest(context);
            else if (context.Request.LocalPath == "/c.aspx")
                HandleAjaxRequest(context);
            else if (context.Request.LocalPath.EndsWith(".jsdata"))
                HandleDynamicStaticContentRequest(context);
            else
                HandleStaticContentRequest(context);

            context.Response.Flush();
            context.Response.End();
            // Console.WriteLine("request finished.");
        }
Esempio n. 27
0
 private void kontrahentEnovaSelect_ValueChanged(object sender, EventArgs e)
 {
     kontrahent = Kontrahent.GetKontrahent(Enova.Business.Old.Core.ContextManager.WebContext, (Enova.API.CRM.Kontrahent)kontrahentEnovaSelect.SelectedItem);
     if (Kontrahent != null)
     {
         int?defaultStatusDopPrzj = Enova.Business.Old.Core.ContextManager.WebContext.GetConfigInt("ZWROT_STATUS_DOPIERO_PRZYJEDZIE");
         if (defaultStatusDopPrzj != null)
         {
             WebContext dc = this.Kontrahent.DbContext != null ? (WebContext)this.Kontrahent.DbContext : Enova.Business.Old.Core.ContextManager.WebContext;
             if (dc.Zwroty.Any(z => z.KontrahentID == this.Kontrahent.ID && z.OstatniStatusID == defaultStatusDopPrzj.Value))
             {
                 BAL.Forms.FormManager.Alert("!!! UWAGA !!! - DLA TEGO KONTRAHENTA ISTNIEJE ZWROT Z USTAWIONYM STATUSEM \"DOPIERO PRZYJEDZIE\"");
             }
         }
     }
 }
Esempio n. 28
0
        private void Launcher_FormClosing(object sender, FormClosingEventArgs e)
        {
            AudioOutputDevice?.Stop();

            AudioOutputDevice?.Dispose();
            BackgroundAudioFile?.Dispose();

            WebContext.Stop();
            WebContext.Dispose();
            UpMan.Kill();

            if (CreditsFile != null)
            {
                CreditsFile.Delete();
            }
        }
Esempio n. 29
0
        public void IdentifySectionHeaderForNoResultsFound() //For invalid staff
        {
            AddressBookSearchPage searchBox = QuickSearch.QuickSearchNavigation();

            searchBox.ClearText();
            searchBox.textSearch.SendKeys(InvalidtextForSearch);
            searchBox.waitForPupilResultstoAppear();
            int    resultCount        = searchBox.CheckForStaffAvailability(InvalidtextForSearch);
            String NoElementtileTitle = SeleniumHelper.Get("result_tile_scroll").Text;

            Assert.True(NoElementtileTitle == AddressBookConstants.TitleForNoResultsfound, "No results found text didn't appear"); //Assertion for title if records are not found
            if (true)
            {
                WebContext.Screenshot();
            }
        }
Esempio n. 30
0
        public void Constructor_NormalPathAndSegmentsWithQueryString_ParsedCorrectly()
        {
            // Assign

            _owinContext.SetupGet(x => x.Request.PathBase).Returns(new PathString(""));
            _owinContext.SetupGet(x => x.Request.Path).Returns(new PathString("/test/?act=foo"));
            _owinContext.SetupGet(x => x.Request.Scheme).Returns("http");
            _owinContext.SetupGet(x => x.Request.Host).Returns(new HostString("mywebsite.com"));

            // Act
            var context = new WebContext(_owinContext.Object);

            // Assert

            Assert.AreEqual("http://mywebsite.com/", context.SiteUrl);
        }
Esempio n. 31
0
        private void LoadSetupMenu()
        {
            IEnumerable <SetupMenuDto> accessableMenus = WebContext.Current.DomainSettingList[CurrentUserContext.User.DomainId].SetupMenus;

            if (accessableMenus != null)
            {
                foreach (SetupMenuDto item in accessableMenus)
                {
                    MenuItem menu = new MenuItem();
                    SetupMenu.Items.Add(menu);
                    menu.Value       = item.StringId;
                    menu.NavigateUrl = ServerPath + item.NavigateUrl;
                    menu.Text        = WebContext.GetLocalizedData(SetupConst.SetupMenuTextKeyFormatString, item.Id, CurrentUserContext.CurrentLanguage.Id, item.MenuText);
                }
            }
        }
Esempio n. 32
0
		public void Constructor_NormalContext_SetCorrectly()
		{
			// Act
			var context = new WebContext(_owinContext.Object);

			// Assert

			Assert.AreEqual(_owinContext.Object, context.Context);
			Assert.AreEqual(_owinContext.Object.Request, context.Request);
			Assert.AreEqual(_owinContext.Object.Response, context.Response);
			Assert.AreEqual(_owinContext.Object.Request.Query, context.Query);
			Assert.AreEqual("http://localhost/mywebsite/", context.SiteUrl);
			Assert.AreEqual("/mywebsite", context.VirtualPath);
			Assert.AreEqual("/", context.Route);
			Assert.IsFalse(context.IsAjax);
		}
Esempio n. 33
0
        public void SchoolDetailsSmokeTest()
        {
            NavigateToSchoolDetails();

            //school details section
            SchoolDetailsPage sdp = new SchoolDetailsPage();

            sdp.OpenSitesAndBuildings();
            sdp.AddSiteAndBuilding();

            AddSiteAndBuildindPopup popup = new AddSiteAndBuildindPopup();

            popup.EnterShortName("Rajesh");
            popup.EnterName("i m the name");
            WebContext.Screenshot();
        }
Esempio n. 34
0
        public void Constructor_NormalContext_SetCorrectly()
        {
            // Act
            var context = new WebContext(_owinContext.Object);

            // Assert

            Assert.AreEqual(_owinContext.Object, context.Context);
            Assert.AreEqual(_owinContext.Object.Request, context.Request);
            Assert.AreEqual(_owinContext.Object.Response, context.Response);
            Assert.AreEqual(_owinContext.Object.Request.Query, context.Query);
            Assert.AreEqual("http://localhost/mywebsite/", context.SiteUrl);
            Assert.AreEqual("/mywebsite", context.VirtualPath);
            Assert.AreEqual("/", context.Route);
            Assert.IsFalse(context.IsAjax);
        }
Esempio n. 35
0
        public static void generate()
        {
            var dbContext = new WebContext();

            for (int i = 4; i < 52; i++)
            {
                MovieRate mr = new MovieRate();
                mr.Rate      = i % 5 + 1;
                mr.MovieId   = 47;
                mr.Id        = i;
                mr.Comment   = "my rate is the only true rate";
                mr.UserLogin = "******" + i.ToString();
                dbContext.MovieRate.Add(mr);
            }
            dbContext.SaveChanges();
        }
        public static void generate()
        {
            var dbContext = new WebContext();

            for (int i = 4; i < 52; i++)
            {
                Comment c = new Comment();
                c.Id        = i;
                c.UserLogin = "******";
                c.Timestamp = 0;
                c.Text      = "some interesting ref";
                c.MovieId   = i;
                dbContext.Comment.Add(c);
            }
            dbContext.SaveChanges();
        }
Esempio n. 37
0
        public override void Run(IHostServer server, WebContext ctx, string callbackEndPoint,
                                 CancellationToken cancel)
        {
            if (null != ctx.User)
            {
                SetCurrentUser(server, ctx.User);
            }
            ctx.ContentEncoding = Encoding.UTF8;
            ctx.SetHeader("Content-Encoding", "utf-8");
            var context = server.Container.Get <IMvcContext>(null, server, ctx, callbackEndPoint, cancel);

            context.NotModified = false;
            try
            {
                if (!Authorize(server, context))
                {
                    return;
                }
                BindContext(context);
                var action = context.ActionDescriptor.Action as ActionBase;
                if (null != action)
                {
                    action.HostServer           = server;
                    action.WebContext           = ctx;
                    action.WebContextParameters = RequestParameters.Create(ctx);
                }
                Execute(context);
                if (context.NotModified)
                {
                    context.StatusCode = 304;
                    ctx.Response.Close();
                }
                else
                {
                    SetModifiedHeader(context);
                    RenderResult(context);
                }
            }
            catch (Exception ex)
            {
                ProcessError(context, ex);
            }
            finally
            {
                context.Release();
            }
        }
Esempio n. 38
0
        public override void Configuration(IAppBuilder app)
        {
            var ctx = new WebContext(new WebContextFactory());
            var ioc = new IOC();

            ServiceProvider.Configure(ioc.Resolver);

            // ServiceProvider.Current.DataAccess.StartUnitOfWork() is not called here. It should be called in each controller action method.
            // This allows more control of when database transactions commit, which solves issues where different processes access the same
            // tables and cause transaction deadlock issues.

            // WebApi setup (includes adding the Authorization filter)
            config = new HttpConfiguration();
            WebApiConfig.Register(config);

            app.UseWebApi(config);
        }
        static void Main(string[] args)
        {
            try
            {
                // Set the path of the config file.
                string configPath = "";

                // Get the Web application configuration object.
                Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

                // Get the section related object.
                HealthMonitoringSection configSection =
                    (HealthMonitoringSection)config.GetSection("system.web/healthMonitoring");

                // Display title and info.
                Console.WriteLine("ASP.NET Configuration Info");
                Console.WriteLine();

                // Display Config details.
                Console.WriteLine("File Path: {0}",
                                  config.FilePath);
                Console.WriteLine("Section Path: {0}",
                                  configSection.SectionInformation.Name);

                // IsMachineLevel property.
                Console.WriteLine("IsMachineLevel: {0}",
                                  config.EvaluationContext.IsMachineLevel);

                // Create an object based on HostingContext.
                WebContext myWC =
                    (WebContext)config.EvaluationContext.HostingContext;
                // Use the WebContext object to determine
                // the ApplicationLevel.
                Console.WriteLine("ApplicationLevel: {0}",
                                  myWC.ApplicationLevel);
            }

            catch (Exception e)
            {
                // Error.
                Console.WriteLine(e.ToString());
            }

            // Display and wait.
            Console.ReadLine();
        }
        protected override void _Do(WebContext context)
        {
            string[] requestParts = context.httprequest.Path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            Account account = context.session.account;
            Thread  thread  = Thread.LoadById(int.Parse(requestParts[2]));

            if (!requestParts[3].StartsWith("p"))
            {
                throw new WrongUrlException();                                              //throw new CriticalException("wrong url");
            }
            Post post = Post.LoadById(int.Parse(requestParts[3].PHPSubstring(1)));

            //if(post.thread.id != thread.id) throw new CriticalException("id mismatch");

            thread.forceMarkAsRead(account, post);
        }
Esempio n. 41
0
        public App()
        {
            this.Startup            += this.Application_Startup;
            this.Exit               += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            MCUser myDefaultUser = new MCUser {
                Name = "Test"
            };

            WebContext webContext = new WebContext();

            webContext.Authentication = new FakeAuthentication(myDefaultUser);
            this.ApplicationLifetimeObjects.Add(webContext);
        }
Esempio n. 42
0
        public override void Run(IHostServer server, WebContext context, string callbackEndPoint,
                                 CancellationToken cancel)
        {
            var abspath = context.Uri.AbsolutePath;

            if (string.IsNullOrWhiteSpace(abspath) || abspath == "/")
            {
                if (!string.IsNullOrWhiteSpace(server.Config.DefaultPage))
                {
                    abspath = server.Config.DefaultPage;
                }
                else
                {
                    abspath = DefaultPage;
                }
            }
            var staticdescriptor = server.Static.Get(abspath, context);

            //в случае, если запрошен HTML и он отсутствует, то в качестве результата возвращаем стартуовую страницу
            //указанного в начале имени приложения (для этого в видимости должен находится скрипт с контроллерами приложения
            if (null == staticdescriptor && abspath.EndsWith(".html"))
            {
                RunApplication(server, context, callbackEndPoint, cancel, abspath);
                return;
            }
            if (null == staticdescriptor && abspath.EndsWith("-starter.js"))
            {
                RunApplicationStarter(server, context, callbackEndPoint, cancel, abspath);
                return;
            }
            if (null == staticdescriptor)
            {
                FinishWirh404(context);
                return;
            }
            if (!string.IsNullOrWhiteSpace(staticdescriptor.Role))
            {
                var roles = server.Container.Get <IRoleResolverService>();
                if (!roles.IsInRole(context.User, staticdescriptor.Role))
                {
                    throw new SecurityException("access denied " + context.User.Identity.Name + " " + staticdescriptor.Role);
                }
            }
            //   context.Response.AddHeader("Accept-Ranges","bytes");
            Finish200(server, context, staticdescriptor);
        }
        public void Test2()
        {
            AuthorizeAttribute a = new AuthorizeAttribute();

            a.Users = "fish, abc";

            string requestText = @"
POST http://www.fish-web-demo.com/Ajax/test/DataTypeTest/Input_int_Add.aspx HTTP/1.1
";
            bool   result      = false;

            using (WebContext context = WebContext.FromRawText(requestText)) {
                context.SetUserName("aaa");
                result = a.AuthenticateRequest(context.HttpContext);
            }
            Assert.AreEqual(false, result);
        }
Esempio n. 44
0
        protected override XElement[] Do(WebContext context)
        {
            Post     post    = Post.LoadById(int.Parse(context.httprequest.Form["postId"]));
            XElement postXml = post.exportToXml(context);

            post.Edit(
                context.session.account.user,
                this.getTitle(context),
                this.getBody(context),
                PostLayer.LoadById(int.Parse(context.httprequest.Form["layerId"]))
                );

            return(new XElement[] {
                post.thread.board.exportToXml(context, Board.SubboardsOptions.None),
                postXml
            });
        }
Esempio n. 45
0
        private void OnRequest(Task <HttpListenerContext> task)
        {
            WebContext wc = null;

            try {
                StartWaitNextRequest();
                wc = task.Result;
                if (CheckInvalidStartupConditions(wc))
                {
                    return;
                }
                PrepareForCrossSiteScripting(task);
                if (CheckOptionsMethodIsCalled(task))
                {
                    return;
                }
                if (wc.Request.ContentLength > Config.MaxRequestSize)
                {
                    throw    new Exception("Exceed max request size");
                }
                CopyCookies(wc);
                Authenticator.Authenticate(wc.Request, wc.Response);
                if (Applications.Application.HasCurrent)
                {
                    Applications.Application.Current.Principal.SetCurrentUser(wc.User);
                }
                var authorization = Authorizer.Authorize(wc.Request);

                if (BeforeHandlerProcessed(wc, authorization))
                {
                    if (!wc.Response.WasClosed)
                    {
                        wc.Response.Close();
                    }
                    return;
                }

                new HostRequestHandler(this, wc).Execute();
            }
            catch (Exception ex) {
                if (!wc.Response.WasClosed)
                {
                    wc.Finish("some error occured " + ex, status: 500);
                }
            }
        }
Esempio n. 46
0
        public Result Post(Cliente cliente)
        {
            try
            {
                using (_context = new WebContext())
                {
                    _context.Add(cliente);
                    _context.SaveChanges();
                }

                return(new Result(true, "Gravado com sucesso", cliente));
            }
            catch (Exception ex)
            {
                return(new Result(false, ex.Message, cliente));
            }
        }
        public void Test_PerformanceMoudle_测试HTTP请求执行超时场景()
        {
            // 测试 HTTP 请求执行超时场景
            using (WebContext context = HttpInfoTest.CreateWebContext()) {
                PerformanceModule module = new PerformanceModule();


                System.Threading.Thread.Sleep(WriterFactory.Config.TimerPeriod + 1000);
                // 暂停异步写入
                SetAsyncWriteEnabled(false);

                // 这个调用仅仅为了覆盖代码,没什么具体意义
                module.Init(context.Application.Instance);

                // 代替 HttpApplicaton 触发 PreRequestHandlerExecute事件
                MethodInfo method = module.GetType().GetMethod("app_PreRequestHandlerExecute", BindingFlags.Instance | BindingFlags.NonPublic);
                method.Invoke(module, new object[] { context.Application.Instance, null });

                // 获取结果,检查上面的调用是否成功
                object value = context.HttpContext.Items["289e8920-b291-4167-80b0-793cd46cad22"];
                Assert.IsTrue(value.GetType() == typeof(DateTime));


                // 模拟超时
                System.Threading.Thread.Sleep(WriterFactory.Config.Performance.HttpExecuteTimeout + 1000);


                // 代替 HttpApplicaton 触发 PostRequestHandlerExecute事件
                method = module.GetType().GetMethod("app_PostRequestHandlerExecute", BindingFlags.Instance | BindingFlags.NonPublic);
                method.Invoke(module, new object[] { context.Application.Instance, null });

                // 获取调用 LogHelper.Write(info); 的数据

                List <PerformanceInfo> list = GetQueueData();

                Assert.AreEqual(1, list.Count);

                PerformanceInfo performanceInfo = list[0];
                Assert.AreEqual("http://www.bing.com/sfdjosfdj/slfjsfj/sdjfosf.aspx", performanceInfo.HttpInfo.Url);

                // 启用异步写入
                SetAsyncWriteEnabled(true);

                module.Dispose();
            }
        }
Esempio n. 48
0
        public void Constructor_VirtualPathWithPort_SetCorrectly()
        {
            // Assign

            _owinContext.SetupGet(x => x.Request.PathBase).Returns(new PathString("/mywebsite"));
            _owinContext.SetupGet(x => x.Request.Path).Returns(new PathString("/"));
            _owinContext.SetupGet(x => x.Request.Scheme).Returns("http");
            _owinContext.SetupGet(x => x.Request.Host).Returns(new HostString("localhost", 8080));

            // Act
            var context = new WebContext(_owinContext.Object);

            // Assert

            Assert.AreEqual("http://localhost:8080/mywebsite/", context.SiteUrl);
            Assert.AreEqual("/mywebsite", context.VirtualPath);
        }
Esempio n. 49
0
        //public ILogonPersionCallBack LogonPersionCallBack;

        public App()
        {
            SystemManageDomainContext = new SystemManageDomainContext();

            this.Startup            += this.Application_Startup;
            this.Exit               += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
            CompositionInitializer.SatisfyImports(this);
            WebContext webContext = new WebContext();

            webContext.Authentication = new FormsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);

            //LogonPersionCallBack = new OnLinePersionCallBack();
        }
Esempio n. 50
0
        protected override HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel)
        {
            var parameters = RequestParameters.Create(context);
            var login      = parameters.Get("login");
            var key        = parameters.Get("key");
            var pass       = parameters.Get("pass");

            if (string.IsNullOrWhiteSpace(login))
            {
                return(GetError("no login", login, pass, key));
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                return(GetError("no key", login, pass, key));
            }
            if (string.IsNullOrWhiteSpace(pass))
            {
                return(GetError("no pass", login, pass, key));
            }
            var user = Users.GetUser(login);

            if (null == user)
            {
                return(GetError("no user", login, pass, key));
            }
            if (!CheckState.IsLogable(user))
            {
                return(GetError("not logable user", login, pass, key));
            }
            var state = CheckState.GetActivityState(user);

            if (state != UserActivityState.Ok)
            {
                return(GetError("invalid state " + state, login, pass, key));
            }

            PasswordManager.ResetPassword(user, pass, key);


            Users.Store(user);

            return(new HandlerResult {
                Result = new { passchanged = true },
                Data = new { passchanged = true, login, key, pass = pass.GetMd5() }
            });
        }
Esempio n. 51
0
        /// <summary>
        /// On received.
        /// </summary>
        /// <param name="context">The base context.</param>
        private void OnReceived(Context context)
        {
            // Create the context.
            WebContext webContext = base.CreateWebContext(context);

            // Create the new http context from the web context.
            Nequeo.Net.Http.HttpContext httpContext = Nequeo.Net.Http.HttpContext.CreateFrom(webContext);

            // Assign response and request data.
            httpContext.HttpResponse        = new HttpResponse();
            httpContext.HttpRequest         = new HttpRequest();
            httpContext.HttpResponse.Output = webContext.WebResponse.Output;
            httpContext.HttpRequest.Input   = webContext.WebRequest.Input;

            // Pass the http context.
            OnHttpContext(httpContext);
        }
Esempio n. 52
0
        public virtual void Run(IHostServer server, WebContext context, string callbackEndPoint,
                                CancellationToken cancel)
        {
            try {
                var result = DefaultProcess(server, context, callbackEndPoint, cancel);

                if (IsUserOperation)
                {
                    if (IsError(result))
                    {
                        if (ErrorLevel != LogLevel.None)
                        {
                            if (UserOpLog.IsFor(ErrorLevel))
                            {
                                var message = GetUserOperationLog(true, ErrorLevel, result, context);
                                UserOpLog.Write(ErrorLevel, message);
                            }
                        }
                    }
                    else
                    {
                        if (SuccessLevel != LogLevel.None)
                        {
                            if (UserOpLog.IsFor(SuccessLevel))
                            {
                                var message = GetUserOperationLog(false, SuccessLevel, result, context);
                                UserOpLog.Write(SuccessLevel, message);
                            }
                        }
                    }
                }
            }
            catch (Exception e) {
                if (ExceptionLevel != LogLevel.None)
                {
                    if (UserOpLog.IsFor(ExceptionLevel))
                    {
                        var message =
                            new { error = true, type = e.GetType().Name, message = e.Message, stack = e.StackTrace }
                        .stringify();
                        UserOpLog.Write(ExceptionLevel, message);
                    }
                }
                throw;
            }
        }
Esempio n. 53
0
        public static bool IsFeatureToggleEnabled(Features feature)
        {
            var            securityConfiguration = new SecurityConfiguration();
            var            internalLogger        = new InternalLogger(securityConfiguration);
            var            webContext            = new WebContext();
            IUserProfileId userProfileId         = new UserProfileId(webContext, internalLogger);

            var jwt = new JwtTokenRequestClient(securityConfiguration, internalLogger, userProfileId, new JwtTokenCache(webContext));

            var securityTokenServiceProxy = new SecurityTokenServiceProxy(jwt, securityConfiguration);
            var httpClientProxy           = new HttpClientProxy(securityTokenServiceProxy);
            var configuration             = new Configuration();
            var restClient    = new RestClient(configuration, httpClientProxy);
            var featureToggle = new FeatureToggle(restClient);

            return(featureToggle.IsEnabled(feature));
        }
Esempio n. 54
0
        public override void Rewrite(WebContext context)
        {
            var url      = context.Request.Uri.ToString();
            var oldquery = context.Request.Uri.Query;
            var newurl   = Regex.Replace(url, Replace);
            var newuri   = new Uri(newurl);
            var newquery = newuri.Query;
            var trgdict  = RequestParameters.ParseQuery(newquery);

            var match = Regex.Match(url);
            var names = Regex.GetGroupNames();

            foreach (var name in names)
            {
                if (!trgdict.ContainsKey(name))
                {
                    trgdict[name] = match.Groups[name].Value;
                }
            }
            var srcdict = RequestParameters.ParseQuery(oldquery);

            foreach (var pair in srcdict)
            {
                if (!trgdict.ContainsKey(pair.Key))
                {
                    trgdict[pair.Key] = pair.Value;
                }
            }
            var asterindex = newurl.IndexOf("?");
            var path       = newurl;

            if (asterindex != -1)
            {
                path = newurl.Substring(0, asterindex);
            }
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            var query = "?" +
                        string.Join("&",
                                    trgdict.Select(_ => Uri.EscapeDataString(_.Key) + "=" + Uri.EscapeDataString(_.Value)));

            newuri = new Uri(path + query);
            context.Request.Uri = newuri;
        }
Esempio n. 55
0
        public async Task <string> AsyncExecuteService(string requestText)
        {
            using (WebContext context = WebContext.FromRawText(requestText)) {
                ServiceHandlerFactory factory = new ServiceHandlerFactory();
                IHttpHandler          handler = factory.GetHandler(context.HttpContext, null, null, null);

                HttpTaskAsyncHandler taskHandler = handler as HttpTaskAsyncHandler;
                if (taskHandler == null)
                {
                    throw new InvalidOperationException();
                }

                await taskHandler.ProcessRequestAsync(context.HttpContext);

                return(context.Response.GetText());
            }
        }
Esempio n. 56
0
        protected override void Reset(ConfigurationElement parentElement)
        {
            PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            WsdlHelpGeneratorElement parent = (WsdlHelpGeneratorElement)parentElement;

#if MONO_BROKEN_CONFIGURATION_DLL
            try {
                var hack = this.EvaluationContext;
            } catch (ConfigurationErrorsException) {
                base.Reset(parentElement);
                this.actualPath = GetConfigurationDirectory();
                return;
            }
#endif
            ContextInformation context    = this.EvaluationContext;
            WebContext         webContext = context.HostingContext as WebContext;
            if (webContext != null)
            {
                string tempVirtualPath = webContext.Path;
                bool   isMachineConfig = tempVirtualPath == null;
                this.actualPath = parent.actualPath;

                if (isMachineConfig)
                {
                    tempVirtualPath = HostingEnvironment.ApplicationVirtualPath;
                }

                if ((tempVirtualPath != null) && !tempVirtualPath.EndsWith("/", StringComparison.Ordinal))
                {
                    tempVirtualPath += "/";
                }

                if ((tempVirtualPath == null) && (parentElement != null))
                {
                    this.virtualPath = parent.virtualPath;
                }
                else if (tempVirtualPath != null)
                {
                    this.virtualPath = tempVirtualPath;
                }
            }

            base.Reset(parentElement);
        }
Esempio n. 57
0
        public App()
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("ru-RU");
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;
            System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

            this.Startup += this.Application_Startup;
            this.UnhandledException += this.Application_UnhandledException;
            WebContext webcontext = new WebContext();
            webcontext.Authentication = new System.ServiceModel.DomainServices.Client.ApplicationServices.WindowsAuthentication();

            LoggerContext context=new LoggerContext();
            Logging.Logger.init(context);

            this.ApplicationLifetimeObjects.Add(webcontext);

            WebContext.Current.Authentication.LoadUser(OnLoadUser_Completed, null);
            InitializeComponent();
        }
Esempio n. 58
0
        public App()
        {
            LogonViewModel = new LogonViewModel();
            MainPageViewModel = new MainPageViewModel();
            LogonUserViewModel = new LogonUserViewModel();
            UserManagerViewModel = new UserManagerViewModel();
            FileTypeManagerViewModel = new FileTypeManagerViewModel();
            TaxPayerTypeManagerViewModel = new TaxPayerTypeManagerViewModel();
            TaxPayerManagerViewModel = new TaxPayerManagerViewModel();
            DocumentManagerViewModel = new DocumentManagerViewModel();

            this.Startup += this.Application_Startup;
            this.UnhandledException += this.Application_UnhandledException;
            this.CheckAndDownloadUpdateCompleted +=new CheckAndDownloadUpdateCompletedEventHandler(App_CheckAndDownloadUpdateCompleted);
            InitializeComponent();
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);
        }
Esempio n. 59
0
        void AsyncReceiveDone(IAsyncResult ar)
        {
            ClientConnectionThread thr = ar.AsyncState as ClientConnectionThread;
            int rd = thr.ClientSocket.EndReceive(ar);
            if (rd > 0)
            {
                string requestdata = Encoding.Default.GetString(thr.buffer, 0, rd);

                WebContext wc = new WebContext();
                wc.Request = WebRequest.Create(requestdata);
                wc.Response = WebResponse.Create(thr.ClientSocket);
                // for (int q = 0; q < 20; q++)
                // {
                // Console.WriteLine("delaying receive in thread #" + Thread.CurrentThread.ManagedThreadId);
                // Thread.Sleep(200);
                // }
                thr.Owner.HandleRequest(wc);
            }
        }
Esempio n. 60
0
        private static void ListAutomationChannelsJSON(WebContext context, Song s)
        {
            JSONWriter jw = new JSONWriter();
            jw.Array();

            for (int j = 0; j < s.Tracks.Count; j++)
            {
                // SongTrack st = s.Tracks[j];
                jw.Class();
                jw.Field("id", j);
                jw.Field("name", "Automation #" + j);
                jw.End();
            }

            jw.End();

            context.Response.Write("g_AutomationTracks = ");
            context.Response.Write(jw.ToString(JSONFormatting.Pretty));
            context.Response.Write(";\n");
        }