コード例 #1
0
        public bool Authenticate(System.ServiceModel.OperationContext operationContext)
        {
            //Extract the Authorization header, and parse out the credentials converting the Base64 string:
            var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];

            AuthenticationHeader header;

            if (AuthenticationHeader.TryDecode(authHeader, out header))
            {
                /*
                 * This would be the place to inject the OAuth authentication manager.
                 */

                if ((header.Username == "user1" && header.Password == "test"))
                {
                    //User is authrized and originating call will proceed
                    return(true);
                }
                else
                {
                    //not authorized
                    return(false);
                }
            }
            else
            {
                //No authorization header was provided, so challenge the client to provide before proceeding:
                WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\" WcfWebHttpIISHostingSample\"");
                throw new WebFaultException(HttpStatusCode.Unauthorized);
            }
        }
コード例 #2
0
        private void AppInstalled(string url)
        {
            System.ServiceModel.OperationContext op = System.ServiceModel.OperationContext.Current;
            var msg    = op.RequestContext.RequestMessage;
            Uri appUrl = msg.Headers.To;


            // get connection string from web.config
            var connString = ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ConnectionString;

            var storageAccount = CloudStorageAccount.Parse(connString);

            // create Queue client
            var client = storageAccount.CreateCloudQueueClient();

            // get Queue reference
            var queue = client.GetQueueReference("addininstalled");

            // create Queue if it doesn't yet exist
            queue.CreateIfNotExists();


            // Create new Message
            var message = new CloudQueueMessage(url + "," + appUrl);

            // Add / Send Message to the Queue
            queue.AddMessage(message);
        }
コード例 #3
0
ファイル: CalculatorHelper.cs プロジェクト: spdavid/SP2016
        public static string GetWebServiceUrl()
        {
            System.ServiceModel.OperationContext op  = System.ServiceModel.OperationContext.Current;
            System.ServiceModel.Channels.Message msg = op.RequestContext.RequestMessage;
            Uri url = msg.Headers.To;

            return(url.ToString());
        }
コード例 #4
0
 public static string GetApplicationID(System.ServiceModel.OperationContext context)
 {
     if (context != null)
     {
         return(context.IncomingMessageHeaders.GetHeader <string>(SESSION_APPLICATION_ID_NAME, SESSION_NS));
     }
     else
     {
         return(SESSION_APPLICATION_ID_NAME);
     }
 }
コード例 #5
0
ファイル: WcfHelper.cs プロジェクト: kurtrips/tc
        public static Profile GetProfileFromContext(System.ServiceModel.OperationContext context)
        {
            Profile profile = new Profile();

            profile.SessionID    = context.IncomingMessageHeaders.GetHeader <string>(SESSION_ID_NAME, SESSION_NS);
            profile.SessionToken = context.IncomingMessageHeaders.GetHeader <string>(SESSION_TOKEN_NAME, SESSION_NS);
            profile.UserID       = context.IncomingMessageHeaders.GetHeader <string>(SESSION_USER_ID_NAME, SESSION_NS);
            profile.UserName     = context.IncomingMessageHeaders.GetHeader <string>(SESSION_USERNAME_NAME, SESSION_NS);
            profile.Culture      = context.IncomingMessageHeaders.GetHeader <string>(SESSION_CULTURE_NAME, SESSION_NS);

            return(profile);
        }
コード例 #6
0
 public void OnReceiveMessage(System.ServiceModel.OperationContext operationContext, System.Activities.ExecutionProperties activityExecutionProperties)
 {
     try
     {
         Guid instanceId = operationContext.IncomingMessageHeaders.GetHeader <Guid>(HeaderName, HeaderNS);
         Console.WriteLine("Received a message from a workflow with instanceId = {0}", instanceId);
     }
     catch (MessageHeaderException)
     {
         Console.WriteLine("This message must not be from a workflow.");
     }
 }
コード例 #7
0
 private string GetClientIP()
 {
     try
     {
         System.ServiceModel.OperationContext                       context  = System.ServiceModel.OperationContext.Current;
         System.ServiceModel.Channels.MessageProperties             prop     = context.IncomingMessageProperties;
         System.ServiceModel.Channels.RemoteEndpointMessageProperty endpoint = prop[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
         return(endpoint.Address);
     }
     catch (Exception ex) {
         log.Error(ex);
     }
     return("");
 }
コード例 #8
0
        public static IPAddress GetIpAddress(System.ServiceModel.OperationContext context)
        {
#if !MONO
            var prop = context.IncomingMessageProperties;
            if (context.IncomingMessageProperties.ContainsKey(RemoteEndpointMessageProperty.Name))
            {
                if (prop[RemoteEndpointMessageProperty.Name] is RemoteEndpointMessageProperty endpoint)
                {
                    return(IPAddress.Parse(endpoint.Address));
                }
            }
#endif
            return(null);
        }
コード例 #9
0
        public LoginInfo Login1(string userId, string password, bool quitOther = false)
        {
            LoginInfo     loginInfo  = new LoginInfo();
            SqlBuilder    builder    = new SqlBuilder("axp.User");
            string        sql        = builder.GetQuerySql(0, "A.Id,A.Name,A.UserImage", string.Format("A.Id={0} And A.Password={1} And A.ISUSE=1", LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(password)));
            LibDataAccess dataAccess = new LibDataAccess();
            string        roleId     = string.Empty;
            bool          exists     = false;

            using (IDataReader reader = dataAccess.ExecuteDataReader(sql))
            {
                if (reader.Read())
                {
                    loginInfo.Id        = LibSysUtils.ToString(reader[0]);
                    loginInfo.Name      = LibSysUtils.ToString(reader[1]);
                    loginInfo.UserImage = LibSysUtils.ToString(reader[2]);
                    exists = true;
                }
            }
            if (exists)
            {
                LibHandle handle = LibHandleCache.Default.IsExistsHandle(LibHandeleType.PC, userId);
                if (handle != null)
                {
                    //LibHandleCache.Default.RemoveHandle(handle.Handle);
                }
                if (!loginInfo.IsUsed)
                {
                    string loginIp = string.Empty;
                    //Zhangkj20161219 增加LoginIp
                    System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current;
                    //对于非WCF的访问context为null
                    if (context != null)
                    {
                        System.ServiceModel.Channels.MessageProperties             properties = context.IncomingMessageProperties;
                        System.ServiceModel.Channels.RemoteEndpointMessageProperty endpoint   = properties[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
                        loginIp = endpoint.Address + ":" + endpoint.Port.ToString();
                    }
                    //创建新的Handle
                    handle = LibHandleCache.Default.GetHandle(string.Empty, LibHandeleType.PC, userId, loginInfo.PersonId, loginInfo.PersonName, roleId, loginIp);
                    if (handle != null)
                    {
                        loginInfo.Handle = handle.Handle;
                    }
                }
            }
            return(loginInfo);
        }
コード例 #10
0
        public static IPAddress GetIpAddress(System.ServiceModel.OperationContext context)
        {
#if !MONO
            var prop = context.IncomingMessageProperties;
            if (context.IncomingMessageProperties.ContainsKey(System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name))
            {
                var endpoint = prop[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name]
                               as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
                if (endpoint != null)
                {
                    return(IPAddress.Parse(endpoint.Address));
                }
            }
#endif
            return(null);
        }
コード例 #11
0
        public EndpointAttributes GetEndpointAttributes(System.ServiceModel.OperationContext operationContext)
        {
            if (!EndpointHost.Config.EnableAccessRestrictions)
            {
                return(default(EndpointAttributes));
            }

            var portRestrictions = default(EndpointAttributes);
            var ipAddress        = GetIpAddress(operationContext);

            portRestrictions |= GetIpAddressEndpointAttributes(ipAddress);

            //TODO: work out if the request was over a secure channel
            //portRestrictions |= request.IsSecureConnection ? PortRestriction.Secure : PortRestriction.InSecure;

            return(portRestrictions);
        }
コード例 #12
0
        /// <summary>
        /// Method source sample taken from here: http://bit.ly/1hUa1LR
        /// </summary>
        protected override bool CheckAccessCore(System.ServiceModel.OperationContext operationContext)
        {
            if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
            {
                return(true);
            }
            //Extract the Authorization header, and parse out the credentials converting the Base64 string:
            var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];

            if ((authHeader != null) && (authHeader != string.Empty) && authHeader.Length > 6) //Todo: refactor into a method
            {
                var svcCredentials = System.Text.ASCIIEncoding.ASCII
                                     .GetString(Convert.FromBase64String(authHeader.Substring(6)))
                                     .Split(':');
                var user = new
                {
                    Name     = svcCredentials[0],
                    Password = svcCredentials[1]
                };
                if ((user.Name == "testuser" && user.Password == "testpassword"))
                {
                    //User is authrized and originating call will proceed
                    return(true);
                }
                else
                {
                    //not authorized
                    FailAuthentication();
                }
            }
            else
            {
                FailAuthentication();
            }
            return(false);
        }
コード例 #13
0
 public void OnSendMessage(System.ServiceModel.OperationContext operationContext)
 {
     operationContext.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader(HeaderName, HeaderNS, this.InstanceId));
 }
コード例 #14
0
        public LoginInfo AppLogin(string userId, string password, string clientId, int clientType, bool quitOther = false)
        {
            LoginInfo loginInfo = new LoginInfo();
            //检查是否具有 AXPUSERAPP数据表,用于判定是否支持移动端App登录
            LibSqlModel sqlModel      = LibSqlModelCache.Default.GetSqlModel("axp.User");
            bool        hasAXPUSERAPP = false;

            if (sqlModel != null && sqlModel.Tables.Count > 1 && sqlModel.Tables[1].TableName.Equals("AXPUSERAPP"))
            {
                hasAXPUSERAPP = true;
            }
            if (hasAXPUSERAPP == false)
            {
                return(loginInfo);//如果没有需要的相关字段则直接返回
            }

            SqlBuilder builder = new SqlBuilder("axp.User");
            string     sql     = string.Format(@"SELECT 
                                        A.PERSONID,
                                        A.ROLEID,
                                        A.WALLPAPER,A.WALLPAPERSTRETCH,B.PERSONNAME,B.PHONENO,B.CORNET,B.HEADPORTRAIT,B.MAIL   
                                        FROM AXPUSER A LEFT JOIN COMPERSON B ON B.PERSONID=A.PERSONID   
                                        WHERE A.USERID={0} and A.USERPASSWORD={1} AND A.ISUSE=1", LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(password));
            //builder.GetQuerySql(0, "A.PERSONID,A.PERSONNAME,A.PHONENO,A.CORNET,A.HEADPORTRAIT,A.MAIL,A.ROLEID,A.WALLPAPER,A.WALLPAPERSTRETCH", string.Format("A.USERID={0} And A.USERPASSWORD={1} And A.ISUSE=1", LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(password)));
            LibDataAccess dataAccess = new LibDataAccess();
            string        roleId     = string.Empty;
            bool          exists     = false;

            using (IDataReader reader = dataAccess.ExecuteDataReader(sql))
            {
                if (reader.Read())
                {
                    loginInfo.PersonId   = LibSysUtils.ToString(reader["PERSONID"]);
                    loginInfo.PersonName = LibSysUtils.ToString(reader["PERSONNAME"]);
                    roleId = LibSysUtils.ToString(reader["ROLEID"]);
                    loginInfo.Wallpaper = LibSysUtils.ToString(reader["WALLPAPER"]);
                    loginInfo.Stretch   = LibSysUtils.ToBoolean(reader["WALLPAPERSTRETCH"]);
                    //20170214 施卢威 增加头像 Email 短号信息
                    loginInfo.Headportrait = LibSysUtils.ToString(reader["HEADPORTRAIT"]);
                    loginInfo.UserEMail    = LibSysUtils.ToString(reader["MAIL"]);
                    loginInfo.Cornet       = LibSysUtils.ToString(reader["CORNET"]);
                    loginInfo.UserPhone    = LibSysUtils.ToString(reader["PHONENO"]);
                    exists = true;
                }
            }
            if (exists)
            {
                #region 帐号与登录设备关联
                string appSql = string.Empty;
                //查询帐号是否已有设备标识
                int isAPPClient = LibSysUtils.ToInt32(dataAccess.ExecuteScalar(string.Format("SELECT COUNT(*) from AXPUSERAPP WHERE USERID = '{0}' and CLIENTTYPE={1}", userId, clientType)));
                if (isAPPClient > 0)
                {
                    //更新设备标识信息
                    appSql = string.Format("UPDATE AXPUSERAPP SET  CLIENTID={1}    WHERE USERID={0} AND CLIENTTYPE={2}", LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(clientId), clientType);
                }
                else
                {
                    int curMaxRowId = LibSysUtils.ToInt32(dataAccess.ExecuteScalar(string.Format("SELECT Max(ROW_ID) from AXPUSERAPP WHERE USERID='{0}'", userId)));
                    //插入账户对应的App设备标识信息。
                    appSql = string.Format("insert into AXPUSERAPP(USERID,ROW_ID,ROWNO,CLIENTTYPE,CLIENTID) values('{0}',{1},{2},{3},'{4}')",
                                           userId, curMaxRowId + 1, curMaxRowId + 1, clientType, clientId, 1);
                }
                dataAccess.ExecuteNonQuery(appSql);

                #endregion

                LibHandle handle = LibHandleCache.Default.IsExistsHandle(LibHandeleType.PC, userId);
                if (handle != null)
                {
                    if (quitOther)
                    {
                        LibHandleCache.Default.RemoveHandle(handle.Handle);
                    }
                    else
                    {
                        loginInfo.IsUsed = true;
                    }
                }
                if (!loginInfo.IsUsed)
                {
                    long currentCount = LibHandleCache.Default.GetCount();
                    long maxUserCount = (long)LibHandleCache.Default.MaxUserCount;
                    if (maxUserCount != -1 && maxUserCount < currentCount)
                    {
                        loginInfo.IsOverUser = true;
                    }
                    else
                    {
                        string loginIp = string.Empty;
                        //Zhangkj20161219 增加LoginIp
                        System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current;
                        //对于非WCF的访问context为null
                        if (context != null)
                        {
                            System.ServiceModel.Channels.MessageProperties             properties = context.IncomingMessageProperties;
                            System.ServiceModel.Channels.RemoteEndpointMessageProperty endpoint   = properties[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
                            loginIp = endpoint.Address + ":" + endpoint.Port.ToString();
                            handle  = LibHandleCache.Default.GetHandle(string.Empty, LibHandeleType.PC, userId, loginInfo.PersonId, loginInfo.PersonName, roleId, loginIp);
                        }
                        else
                        {
                            handle = LibHandleCache.Default.GetHandle(string.Empty, LibHandeleType.PC, userId, loginInfo.PersonId, loginInfo.PersonName, roleId);
                        }
                        //创建新的Handle

                        if (handle != null)
                        {
                            loginInfo.Handle = handle.Handle;
                        }
                    }
                }
            }
            return(loginInfo);
        }
コード例 #15
0
 void IAttachable.Detach(System.ServiceModel.OperationContext context)
 {
 }
コード例 #16
0
        public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            SPRemoteEventResult result = new SPRemoteEventResult();

            //get the host web url
            Uri hostUrl = properties.AppEventProperties.HostWebFullUrl;

            //get the operation context so we can figure out the host URL for this service, from
            //which we can get the Authority for a client context
            System.ServiceModel.OperationContext oc = System.ServiceModel.OperationContext.Current;

            Uri localUrl = null;

            //UPDATE:  THIS CODE WORKED FINE FOR WHEN YOU USE THE WEB APP CREATED BY VS.NET
            //FOR THE SHAREPOINT APP, BUT IT BREAKS WHEN YOU DEPLOY TO A REAL IIS SERVER
            //BECAUSE YOU END UP GETTING TWO BASEADDRESSES, BUT NOT WITH THE RIGHT SCHEME.
            //FOR EXAMPLE, THE FIRST ONE IS THE ADDRESS OF THIS HOST BUT WITH THE HTTP SCHEME.
            //THE SECOND ONE IS HTTPS, BUT THE HOST NAME IS THE FQDN OF THE SERVER.  SINCE
            //SHAREPOINT DOESN'T RECOGNIZE THAT AS THE ENDPOINT IT TRUSTS FOR THIS CODE, IT BLOWS
            //UP WHEN RUNNING THE CODE BELOW AND THE WHOLE THING FAILS

            #region Code That Breaks In IIS
            ////now enumerate through the Host base addresses and look for the SSL connection
            //foreach (Uri u in oc.Host.BaseAddresses)
            //{
            //    if (u.Scheme.ToLower() == "https")
            //    {
            //        localUrl = u;
            //        break;
            //    }
            //}
            #endregion

            //assume first base address is ours, which it has been so far
            if (oc.Host.BaseAddresses.Count > 0)
            {
                localUrl = oc.Host.BaseAddresses[0];
            }

            //make sure we found our local URL
            if (localUrl != null)
            {
                //using (ClientContext ctx = TokenHelper.CreateAppEventClientContext(properties, false))
                using (ClientContext ctx = TokenHelper.GetClientContextWithContextToken(hostUrl.ToString(), properties.ContextToken, localUrl.Authority))
                {
                    if (ctx != null)
                    {
                        //try to retrieve the list first to see if it exists
                        List l = ctx.Web.Lists.GetByTitle(LIST_NAME);
                        ctx.Load(l);

                        //have to put in a try block because of course it throw an exception if
                        //list doesn't exist
                        try
                        {
                            ctx.ExecuteQuery();
                        }
                        catch (Exception noListEx)
                        {
                            //look to see if the exception is that the list doesn't exist
                            if (noListEx.Message.ToLower().Contains("does not exist"))
                            {
                                //code here to create list
                                Web web = ctx.Web;

                                ListCreationInformation ci = new ListCreationInformation();
                                ci.Title             = LIST_NAME;
                                ci.TemplateType      = (int)ListTemplateType.GenericList;
                                ci.QuickLaunchOption = QuickLaunchOptions.Off;

                                l             = web.Lists.Add(ci);
                                l.Description = "List for tracking events with the Event Planner Social App";

                                Field fldEventName   = l.Fields.AddFieldAsXml("<Field DisplayName='EventName' Type='Text' />", true, AddFieldOptions.DefaultValue);
                                Field fldSiteUrl     = l.Fields.AddFieldAsXml("<Field DisplayName='SiteUrl' Type='Text' />", true, AddFieldOptions.DefaultValue);
                                Field fldTwitterTags = l.Fields.AddFieldAsXml("<Field DisplayName='TwitterTags' Type='Text' />", true, AddFieldOptions.DefaultValue);

                                Field         fldEventDate = l.Fields.AddFieldAsXml("<Field DisplayName='EventDate' Type='DateTime' />", true, AddFieldOptions.DefaultValue);
                                FieldDateTime dtEventDate  = ctx.CastTo <FieldDateTime>(fldEventDate);
                                dtEventDate.DisplayFormat = DateTimeFieldFormatType.DateOnly;
                                dtEventDate.Update();

                                Field     fldGraphID = l.Fields.AddFieldAsXml("<Field DisplayName='ObjectGraphID' Type='Text' />", true, AddFieldOptions.DefaultValue);
                                FieldText txtGraphID = ctx.CastTo <FieldText>(fldGraphID);
                                txtGraphID.Indexed = true;
                                txtGraphID.Update();

                                l.Hidden = true;
                                l.Update();

                                try
                                {
                                    //this creates the list
                                    ctx.ExecuteQuery();

                                    //all of the rest of this is to remove the list from the "Recent" list that appears
                                    //in sites by default, which is really a set of navigation links

                                    //get the site and root web, where the navigation lives
                                    Site s  = ctx.Site;
                                    Web  rw = s.RootWeb;

                                    //get the QuickLaunch navigation, which is where the Recent nav lives
                                    ctx.Load(rw, x => x.Navigation, x => x.Navigation.QuickLaunch);
                                    ctx.ExecuteQuery();

                                    //now extract the Recent navigation node from the collection
                                    var vNode = from NavigationNode nn in rw.Navigation.QuickLaunch
                                                where nn.Title == "Recent"
                                                select nn;

                                    NavigationNode nNode = vNode.First <NavigationNode>();

                                    //now we need to get the child nodes of Recent, that's where our list should be found
                                    ctx.Load(nNode.Children);
                                    ctx.ExecuteQuery();

                                    var vcNode = from NavigationNode cn in nNode.Children
                                                 where cn.Title == LIST_NAME
                                                 select cn;

                                    //now that we have the node representing our list, delete it
                                    NavigationNode cNode = vcNode.First <NavigationNode>();
                                    cNode.DeleteObject();

                                    ctx.ExecuteQuery();
                                }
                                catch (Exception newListFailEx)
                                {
                                    Debug.WriteLine("Creation of new list failed: " + newListFailEx.Message);
                                }
                            }
                        }

                        //okay, so if we're here then the list should exist, and we should be good to go at this point
                    }
                }
            }


            #region OOB Template Code
            //using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false))
            //{
            //    if (clientContext != null)
            //    {
            //        clientContext.Load(clientContext.Web);
            //        clientContext.ExecuteQuery();
            //    }
            //}
            #endregion

            return(result);
        }
コード例 #17
0
        public LoginInfo Login(string userId, string password, bool quitOther = false)
        {
            LoginInfo     loginInfo  = new LoginInfo();
            SqlBuilder    builder    = new SqlBuilder("axp.User");
            string        sql        = builder.GetQuerySql(0, "A.PERSONID,A.PERSONNAME,A.ROLEID,A.WALLPAPER,A.WALLPAPERSTRETCH", string.Format("A.USERID={0} And A.USERPASSWORD={1} And A.ISUSE=1", LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(password)));
            LibDataAccess dataAccess = new LibDataAccess();
            string        roleId     = string.Empty;
            bool          exists     = false;

            using (IDataReader reader = dataAccess.ExecuteDataReader(sql))
            {
                if (reader.Read())
                {
                    loginInfo.PersonId   = LibSysUtils.ToString(reader[0]);
                    loginInfo.PersonName = LibSysUtils.ToString(reader[1]);
                    roleId = LibSysUtils.ToString(reader[2]);
                    loginInfo.Wallpaper = LibSysUtils.ToString(reader[3]);
                    loginInfo.Stretch   = LibSysUtils.ToBoolean(reader[4]);
                    exists = true;
                }
            }
            if (exists)
            {
                LibHandle handle = LibHandleCache.Default.IsExistsHandle(LibHandeleType.PC, userId);
                if (handle != null)
                {
                    if (quitOther)
                    {
                        LibHandleCache.Default.RemoveHandle(handle.Handle);
                    }
                    else
                    {
                        loginInfo.IsUsed = true;
                    }
                }
                if (!loginInfo.IsUsed)
                {
                    long currentCount = LibHandleCache.Default.GetCount();
                    long maxUserCount = (long)LibHandleCache.Default.MaxUserCount;
                    if (maxUserCount != -1 && maxUserCount < currentCount)
                    {
                        loginInfo.IsOverUser = true;
                    }
                    else
                    {
                        string loginIp = string.Empty;
                        //Zhangkj20161219 增加LoginIp
                        System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current;
                        //对于非WCF的访问context为null
                        if (context != null)
                        {
                            System.ServiceModel.Channels.MessageProperties             properties = context.IncomingMessageProperties;
                            System.ServiceModel.Channels.RemoteEndpointMessageProperty endpoint   = properties[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
                            loginIp = endpoint.Address + ":" + endpoint.Port.ToString();
                        }
                        //创建新的Handle
                        handle = LibHandleCache.Default.GetHandle(string.Empty, LibHandeleType.PC, userId, loginInfo.PersonId, loginInfo.PersonName, roleId, loginIp);
                        if (handle != null)
                        {
                            loginInfo.Handle = handle.Handle;
                        }
                    }
                }
            }
            return(loginInfo);
        }
コード例 #18
0
 public WebOperationContext(System.ServiceModel.OperationContext operationContext)
 {
 }
コード例 #19
0
 public void Detach(System.ServiceModel.OperationContext owner)
 {
 }
コード例 #20
0
        object Process(System.Reflection.MethodBase method, string operationName, bool isAsync, ref object[] parameters, System.ServiceModel.OperationContext context)
        {
            var previousContext = System.ServiceModel.OperationContext.Current;

            try
            {
                System.ServiceModel.OperationContext.Current = context;
                return(DoProcess(method, operationName, isAsync, ref parameters, context));
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                System.ServiceModel.OperationContext.Current = previousContext;
            }
        }
コード例 #21
0
        public object Process(System.Reflection.MethodBase method, string operationName, object[] parameters, System.ServiceModel.OperationContext context)
        {
            var p      = parameters;
            var retval = Process(method, operationName, false, ref p, context);

            if (p != parameters)
            {
                throw new InvalidOperationException();
            }
            return(retval);
        }
コード例 #22
0
        object DoProcess(System.Reflection.MethodBase method, string operationName, bool isAsync, ref object[] parameters, System.ServiceModel.OperationContext context)
        {
            if (AllowInitializationUI)
            {
                DisplayInitializationUI();
            }
            OperationDescription od = SelectOperation(method, operationName, parameters);

            if (State != System.ServiceModel.CommunicationState.Opened)
            {
                Open();
            }
            if (!od.IsOneWay)
            {
                return(Request(od, isAsync, ref parameters, context));
            }
            else
            {
                Output(od, parameters, context);
                return(null);
            }
        }
コード例 #23
0
        /// <summary>
        /// For the request, determine if the requestor's IP address is valid.
        /// </summary>
        /// <param name="auth">An authentication configuration instance.</param>
        /// <param name="authModule">The authentication module instance to use to authenticate the user for the operation.</param>
        /// <param name="operation">The operation that is being requested.</param>
        /// <param name="opContext">The OperationContext for the request (note: this is not the WebOperationContext used for other calls).</param>
        /// <returns>An errordetail instance holding any error that was encountered, or null if no errors were encountered.</returns>
        private static errordetail AuthorizeIPAddressForUser(AuthenticationConfig auth, OttaMattaAuthentication authModule, string operation, System.ServiceModel.OperationContext opContext)
        {
            errordetail  result = null;
            const string endpointPropertyName = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
            bool         failIfNoIP           = false;

            System.ServiceModel.Channels.MessageProperties properties = opContext.IncomingMessageProperties;
            if (properties.ContainsKey(endpointPropertyName))
            {
                RemoteEndpointMessageProperty endpoint = properties[endpointPropertyName] as RemoteEndpointMessageProperty;

                //
                // Note: on local dev machines this is the IPv6 address, like "fe80::c513:967d:1b57:8c33%11".
                //
                string ipAddress = endpoint.Address;

                //
                // We have an IP address.  Let's see if it's authorized for this user.
                //
                if (authModule != null && auth.UserAllowedIps.ContainsKey(authModule.Username))
                {
                    bool ipOK = auth.UserAllowedIps[authModule.Username].Contains(ipAddress);

                    if (!ipOK)
                    {
                        result = new errordetail(string.Format("The IP address \"{0}\" is not authorized for user account \"{1}\"", ipAddress, authModule.Username), HttpStatusCode.Forbidden);
                    }
                }
                else
                {
                    //
                    // There are no IP address restrictions for this account.
                    //
                }
            }
            else
            {
                //
                // Can't get the remote IP from the system.  We can assume that something has changed in the WCF .NET codebase, and allow it for now.
                // Or, we can fail the request.
                //
                if (failIfNoIP)
                {
                    result = new errordetail("Unable to determine request IP address", HttpStatusCode.InternalServerError);
                }
            }

            return(result);
        }
コード例 #24
0
 void Output(OperationDescription od, object[] parameters, System.ServiceModel.OperationContext context)
 {
     System.ServiceModel.Dispatcher.ClientOperation op = runtime.Operations[od.Name];
     Send(CreateRequest(op, parameters, context), OperationTimeout);
 }
コード例 #25
0
        object Request(OperationDescription od, bool isAsync, ref object[] parameters, System.ServiceModel.OperationContext context)
        {
            System.ServiceModel.Dispatcher.ClientOperation op = runtime.Operations[od.Name];
            object[] inspections = new object[runtime.MessageInspectors.Count];
            Message  req         = CreateRequest(op, parameters, context);

            for (int i = 0; i < inspections.Length; i++)
            {
                inspections[i] = runtime.MessageInspectors[i].BeforeSendRequest(ref req, this);
            }
            Message res = Request(req, OperationTimeout);

            if (res.IsFault)
            {
                var          resb  = res.CreateBufferedCopy(runtime.MaxFaultSize);
                MessageFault fault = MessageFault.CreateFault(resb.CreateMessage(), runtime.MaxFaultSize);
                var          conv  = OperationChannel.GetProperty <FaultConverter>() ?? FaultConverter.GetDefaultFaultConverter(res.Version);
                Exception    ex;
                if (!conv.TryCreateException(resb.CreateMessage(), fault, out ex))
                {
                    if (fault.HasDetail)
                    {
                        Type detailType = typeof(System.ServiceModel.ExceptionDetail);
                        var  freader    = fault.GetReaderAtDetailContents();
                        System.Runtime.Serialization.DataContractSerializer ds = null;
                        foreach (var fci in op.FaultContractInfos)
                        {
                            if (res.Headers.Action == fci.Action || GetSerializer(fci).IsStartObject(freader))
                            {
                                detailType = fci.Detail;
                                ds         = GetSerializer(fci);
                                break;
                            }
                        }
                        if (ds == null)
                        {
                            ds = new System.Runtime.Serialization.DataContractSerializer(detailType);
                        }
                        var detail = ds.ReadObject(freader);
                        ex = (Exception)Activator.CreateInstance(typeof(System.ServiceModel.FaultException <>).MakeGenericType(detailType), new object[] {
                            detail,
                            fault.Reason,
                            fault.Code,
                            res.Headers.Action
                        });
                    }
                    if (ex == null)
                    {
                        ex = new System.ServiceModel.FaultException(fault);
                    }
                }
                throw ex;
            }
            for (int i = 0; i < inspections.Length; i++)
            {
                runtime.MessageInspectors[i].AfterReceiveReply(ref res, inspections[i]);
            }
            if (!op.DeserializeReply)
            {
                return(res);
            }
            if (isAsync && od.EndMethod != null)
            {
                var endParams = od.EndMethod.GetParameters();
                parameters = new object[endParams.Length - 1];
            }
            return(op.Formatter.DeserializeReply(res, parameters));
        }
コード例 #26
0
        Message CreateRequest(System.ServiceModel.Dispatcher.ClientOperation op, object[] parameters, System.ServiceModel.OperationContext context)
        {
            MessageVersion version = message_version;

            if (version == null)
            {
                version = MessageVersion.Default;
            }
            Message msg;

            if (op.SerializeRequest)
            {
                msg = op.Formatter.SerializeRequest(version, parameters);
            }
            else
            {
                if (parameters.Length != 1)
                {
                    throw new ArgumentException(String.Format("Argument parameters does not match the expected input. It should contain only a Message, but has {0} parameters", parameters.Length));
                }
                if (!(parameters[0] is Message))
                {
                    throw new ArgumentException(String.Format("Argument should be only a Message, but has {0}", parameters[0] != null ? parameters[0].GetType().FullName : "null"));
                }
                msg = (Message)parameters[0];
            }
            context = context ?? System.ServiceModel.OperationContext.Current;
            if (context != null)
            {
                foreach (var mh in context.OutgoingMessageHeaders)
                {
                    int x = msg.Headers.FindHeader(mh.Name, mh.Namespace, mh.Actor);
                    if (x >= 0)
                    {
                        msg.Headers.RemoveAt(x);
                    }
                    msg.Headers.Add((MessageHeader)mh);
                }
                msg.Properties.CopyProperties(context.OutgoingMessageProperties);
            }
            msg.Properties.AllowOutputBatching = AllowOutputBatching;
            if (msg.Version.Addressing.Equals(AddressingVersion.WSAddressing10))
            {
                if (msg.Headers.MessageId == null)
                {
                    msg.Headers.MessageId = new System.Xml.UniqueId();
                }
                if (msg.Headers.ReplyTo == null)
                {
                    msg.Headers.ReplyTo = new System.ServiceModel.EndpointAddress(Constants.WsaAnonymousUri);
                }
                if (msg.Headers.To == null && RemoteAddress != null)
                {
                    msg.Headers.To = RemoteAddress.Uri;
                }
            }
            return(msg);
        }