public static object CallByName(object Instance, string MethodName, CallType UseCallType, params object[] Arguments)
        {
            switch (UseCallType)
            {
                case CallType.Method:
                    return NewLateBinding.LateCall(Instance, null, MethodName, Arguments, null, null, null, false);

                case CallType.Get:
                    return NewLateBinding.LateGet(Instance, null, MethodName, Arguments, null, null, null);

                case CallType.Let:
                case CallType.Set:
                {
                    IDynamicMetaObjectProvider instance = IDOUtils.TryCastToIDMOP(Instance);
                    if (instance == null)
                    {
                        NewLateBinding.LateSet(Instance, null, MethodName, Arguments, null, null, false, false, UseCallType);
                        break;
                    }
                    IDOBinder.IDOSet(instance, MethodName, null, Arguments);
                    break;
                }
                default:
                    throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "CallType" }));
            }
            return null;
        }
Пример #2
0
        void MakeHttpRequest(string remoteUrl, CallType callType, NameValueCollection headers, byte[] buffer)
        {
            headers[HeaderMapper.NServiceBus + HeaderMapper.CallType] = Enum.GetName(typeof(CallType), callType);
            headers[HttpHeaders.ContentMd5Key] = Hasher.Hash(buffer);
            headers["NServiceBus.Gateway"] = "true";

            headers[HttpHeaders.FromKey] = ListenUrl;

            var request = WebRequest.Create(remoteUrl);
            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers = Encode(headers);

            request.ContentLength = buffer.Length;

            var stream = request.GetRequestStream();
            stream.Write(buffer, 0, buffer.Length);

            Logger.DebugFormat("Sending message - {0} to: {1}", callType, remoteUrl);
            int statusCode;

            using (var response = request.GetResponse() as HttpWebResponse)
                statusCode = (int)response.StatusCode;

            Logger.Debug("Got HTTP response with status code " + statusCode);

            if (statusCode != 200)
            {
                Logger.Warn("Message not transferred successfully. Trying again...");
                throw new Exception("Retrying");
            }
        }
Пример #3
0
		/// <summary>
		/// Allows late bound invocation of
		/// properties and methods.
		/// </summary>
		/// <param name="target">Object implementing the property or method.</param>
		/// <param name="methodName">Name of the property or method.</param>
		/// <param name="callType">Specifies how to invoke the property or method.</param>
		/// <param name="args">List of arguments to pass to the method.</param>
		/// <returns>The result of the property or method invocation.</returns>
		public static object CallByName(
		  object target, string methodName, CallType callType,
		  params object[] args)
		{
			switch (callType)
			{
				case CallType.Get:
					{
						PropertyInfo p = target.GetType().GetProperty(methodName);
						return p.GetValue(target, args);
					}
				case CallType.Let:
				case CallType.Set:
					{
						PropertyInfo p = target.GetType().GetProperty(methodName);
						object[] index = null;
						if (args.Length > 1)
						{
							index = new object[args.Length - 1];
							args.CopyTo(index, 1);
						}
						p.SetValue(target, args[0], index);
						return null;
					}
				case CallType.Method:
					{
						MethodInfo m = target.GetType().GetMethod(methodName);
						return m.Invoke(target, args);
					}
			}
			return null;
		}
Пример #4
0
Файл: Call.cs Проект: 7shi/LLPML
 public static void AddCallCodes2(
     OpModule codes, NodeBase[] args, CallType type, Action delg)
 {
     for (int i = args.Length - 1; i >= 0; i--)
         args[i].AddCodesV(codes, "push", null);
     delg();
     if (type == CallType.CDecl && args.Length > 0)
     {
         int p = 4;
         bool pop = false;
         for (int i = 0; i < args.Length; i++)
         {
             var arg = args[i];
             if (OpModule.NeedsDtor(arg))
             {
                 if (!pop)
                 {
                     codes.Add(I386.Push(Reg32.EAX));
                     pop = true;
                 }
                 arg.Type.AddDestructorA(codes, Addr32.NewRO(Reg32.ESP, p));
             }
             p += 4;
         }
         if (pop) codes.Add(I386.Pop(Reg32.EAX));
         codes.Add(I386.AddR(Reg32.ESP, Val32.New((byte)(args.Length * 4))));
     }
 }
Пример #5
0
	// Perform a late bound call.
	public static Object CallByName
				(Object ObjectRef, String ProcName,
				 CallType UseCallType, Object[] Args)
			{
				switch(UseCallType)
				{
					case CallType.Method:
					{
						return LateBinding.LateCallWithResult
							(ObjectRef, null, ProcName, Args, null, null);
					}
					// Not reached.

					case CallType.Get:
					{
						return LateBinding.LateGet
							(ObjectRef, null, ProcName, Args, null, null);
					}
					// Not reached.

					case CallType.Set:
					case CallType.Let:
					{
						LateBinding.LateSet
							(ObjectRef, null, ProcName, Args, null);
						return null;
					}
					// Not reached.
				}
				throw new ArgumentException(S._("VB_InvalidCallType"));
			}
Пример #6
0
 public override ICallControl Call(string phoneNumber, CallType type)
 {
     if (CallType.Voice.Equals (type)) {
         using (var pool = new NSAutoreleasePool ()) {
             StringBuilder filteredPhoneNumber = new StringBuilder();
             if (phoneNumber!=null && phoneNumber.Length>0) {
                 foreach (char c in phoneNumber) {
                     if (Char.IsNumber(c) || c == '+' || c == '-' || c == '.') {
                         filteredPhoneNumber.Append(c);
                     }
                 }
             }
             String textURI = "tel:" + filteredPhoneNumber.ToString();
             var thread = new Thread (InitiateCall);
             thread.Start (textURI);
         }
         ;
     } else {
         INotification notificationService = (INotification)IPhoneServiceLocator.GetInstance ().GetService ("notify");
         if (notificationService != null) {
             notificationService.StartNotifyAlert ("Phone Alert", "The requested call type is not enabled or supported on this device.", "OK");
         }
     }
     return null;
 }
Пример #7
0
 public Call(DateTime startCall, DateTime endCall, string phoneNumber, CallType callType = CallType.Dailed)
 {
     this.startCallDateTime = startCall;
     this.endCallDateTime = endCall;
     this.phoneNumber = phoneNumber;
     this.PhoneCallType = callType;
 }
Пример #8
0
		internal void InitMessage (MonoMethod method, object [] out_args)
		{
			this.method = method;
			ParameterInfo[] paramInfo = method.GetParametersInternal ();
			int param_count = paramInfo.Length;
			args = new object[param_count];
			arg_types = new byte[param_count];
			asyncResult = null;
			call_type = CallType.Sync;
			names = new string[param_count];
			for (int i = 0; i < param_count; i++) {
				names[i] = paramInfo[i].Name;
			}
			bool hasOutArgs = out_args != null;
			int j = 0;
			for (int i = 0; i < param_count; i++) {
				byte arg_type;
				bool isOut = paramInfo[i].IsOut;
				if (paramInfo[i].ParameterType.IsByRef) {
					if (hasOutArgs)
						args[i] = out_args[j++];
					arg_type = 2; // OUT
					if (!isOut)
						arg_type |= 1; // INOUT
				} else {
					arg_type = 1; // IN
					if (isOut)
						arg_type |= 4; // IN, COPY OUT
				}
				arg_types[i] = arg_type;
			}
		}
Пример #9
0
 public static TypeDelegate New(
     BlockBase parent, CallType callType, TypeBase retType, VarDeclare[] args)
 {
     var ret = new TypeDelegate();
     ret.init(callType, retType, args);
     ret.Parent = parent;
     return ret;
 }
Пример #10
0
 public MethodCandidate MakeBindingTarget(CallType callType, Type[] types, out Type[] argumentTests) {
     TargetSet ts = GetTargetSet(types.Length);
     if (ts != null) {
         return ts.MakeBindingTarget(callType, types, _kwArgs, out argumentTests);
     }
     argumentTests = null;
     return null;
 }
Пример #11
0
 public ReportRecord(CallType callType, int number, DateTime date, DateTime time, int cost)
 {
     CallType = callType;
     Number = number;
     Date = date;
     Time = time;
     Cost = cost;
 }
Пример #12
0
 public AbstractValue AbstractCall(CallType callType, IList<AbstractValue> args) {
     TargetSet ts = this.GetTargetSet(args.Count);
     if (ts != null) {
         return ts.AbstractCall(callType, args);
     } else {
         return AbstractValue.TypeError(BadArgumentCount(callType, args.Count).Message);
     }
 } 
Пример #13
0
        void Transmit(IChannelSender channelSender, Site targetSite, CallType callType, IDictionary<string,string> headers, Stream data)
        {
            headers[HeaderMapper.NServiceBus + HeaderMapper.CallType] = Enum.GetName(typeof(CallType), callType);
            headers[HttpHeaders.ContentMd5Key] = Hasher.Hash(data);

            Logger.DebugFormat("Sending message - {0} to: {1}", callType, targetSite.Address);

            channelSender.Send(targetSite.Address, headers, data);
        }
 public override async Task Call(string number, CallType type)
 {
     if (String.IsNullOrWhiteSpace(number) || type != CallType.Voice) return;
     if (
         !number.All(
             character => char.IsDigit(character) || character == '+' || character == '*' || character == '#' || character == ' '))
         return;
     if (AppverseBridge.Instance.RuntimeHandler.Webview.Dispatcher.HasThreadAccess) PhoneCallManager.ShowPhoneCallUI(number, String.Empty);
     else await AppverseBridge.Instance.RuntimeHandler.Webview.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => PhoneCallManager.ShowPhoneCallUI(number, String.Empty));
 }
        void Transmit(IChannelSender channelSender, Site targetSite, CallType callType,
            IDictionary<string, string> headers, Stream data)
        {
            headers[GatewayHeaders.IsGatewayMessage] = Boolean.TrueString;
            headers["NServiceBus.CallType"] = Enum.GetName(typeof(CallType), callType);
            headers[HttpHeaders.ContentMD5] = Hasher.Hash(data);

            Logger.DebugFormat("Sending message - {0} to: {1}", callType, targetSite.Channel.Address);

            channelSender.Send(targetSite.Channel.Address, headers, data);
        }
Пример #16
0
 public static CallProvider Create(CallType type, IUnitOfWork unitOfWork, IEmailHelper emailHelper)
 {
     switch (type)
     {
         case CallType.Telesale:
             return new TelesaleCallProvider(unitOfWork, emailHelper);
         case CallType.BD:
             return new BdCallProvider(unitOfWork, emailHelper);
         default:
             throw new Exception("Incorrect call type");
     }
 }
Пример #17
0
        private async Task<JObject> CallAPI(string endpoint, CallType callType, JObject payload = null)
        {
            JObject result = null;
            HttpClient client = null;

            try
            {
                client = new HttpClient();

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = null;
                string fullPathEndpoint = Path.Combine(_requestUri, endpoint);
                Console.WriteLine("Calling " + fullPathEndpoint + "...");

                if (callType == CallType.POST)
                {
                    HttpContent httpContent = null;
                    if (payload != null)
                    {
                        httpContent = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
                        //Console.WriteLine("Call Payload: " + payload.ToString());
                    }

                    response = await client.PostAsync(fullPathEndpoint, httpContent);
                }
                else
                {
                    response = await client.GetAsync(fullPathEndpoint);
                }

                string responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response Code: " + response.StatusCode.ToString());
                //Console.WriteLine("Call Response: " + responseString);
                if (response.IsSuccessStatusCode)
                {
                    if (!string.IsNullOrEmpty(responseString)) result = JObject.Parse(responseString);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Call Exception: " + ex.Message);
            }
            finally
            {
                if (client != null)
                    client.Dispose();
            }

            return result;
        }
Пример #18
0
        public Call(Seat bidder, CallType type, Bid bid = null)
        {
            if (bidder == Seat.None)
                throw new ArgumentException("Bidder must not be none.");
            if (type == CallType.None)
                throw new ArgumentException("Call type must not be none.");
            if (type == CallType.Bid && bid == null)
                throw new ArgumentException("Bid must not be null when call type is bid.");

            Bidder = bidder;
            CallType = type;
            Bid = bid;
        }
Пример #19
0
        /// <summary>
        /// return next call base on supplied informations
        /// </summary>
        /// <param name="type">type of call provider</param>
        /// <param name="initial">initial for find next call, ignored if siteId is supplied</param>
        /// <param name="siteId">siteId for find next call</param>
        /// <param name="lastCallId">Qccupied call id</param>
        /// <returns></returns>
        public CallDetail GetNextCall(CallType type, string initial, int? siteId, int? lastCallId)
        {
            var provider = GetProvider(type);
            if (lastCallId.HasValue)
                _contactService.RemoveOccupiedCall(lastCallId.Value);

            if (siteId.HasValue)
                return provider.GroupCall.Next(initial, siteId.Value);

            if (!string.IsNullOrEmpty(initial))
                return provider.StandardCall.Next(initial);

            return null;
        }
Пример #20
0
 private CallType CheckCallType(CallType ct, string[] t)
 {
     if (t[0] == "__stdcall")
     {
         t[0] = Read();
         return CallType.Std;
     }
     else if (t[0] == "__cdecl")
     {
         t[0] = Read();
         return CallType.CDecl;
     }
     return ct;
 }
Пример #21
0
 public static string CallTypeToString(CallType callType)
 {
     switch (callType)
     {
         case CallType.Any:
             return "A";
         case CallType.Inbound:
             return "I";
         case CallType.Outbound:
             return "O";
         default:
             throw new ArgumentOutOfRangeException("callType");
     }
 }
Пример #22
0
        /// <summary>
        /// Generates stub to receive the CLR call and then call the dynamic language code.
        /// </summary>
        public static void  EmitClrCallStub(CodeGen cg, Slot callTarget, int firstArg, CallType functionAttributes) {
            List<ReturnFixer> fixers = new List<ReturnFixer>(0);
            IList<Slot> args = cg.ArgumentSlots;
            int nargs = args.Count - firstArg;
            
            CallAction action;
            if ((functionAttributes & CallType.ArgumentList) != 0) {
                ArgumentInfo[] infos = CompilerHelpers.MakeRepeatedArray(ArgumentInfo.Simple, nargs);
                infos[nargs - 1] = new ArgumentInfo(ArgumentKind.List);

                action = CallAction.Make(new CallSignature(infos));
            } else {
                action = CallAction.Make(nargs);
            }

            bool fast;
            Slot site = cg.CreateDynamicSite(action, 
                CompilerHelpers.MakeRepeatedArray(typeof(object), nargs + 2), 
                out fast);

            site.EmitGet(cg);
            if (!fast) cg.EmitCodeContext();

            if (DynamicSiteHelpers.IsBigTarget(site.Type)) {
                cg.EmitTuple(site.Type.GetGenericArguments()[0], args.Count + 1, delegate(int index) {
                    if (index == 0) {
                        callTarget.EmitGet(cg);
                    } else {
                        ReturnFixer rf = ReturnFixer.EmitArgument(cg, args[index - 1]);
                        if (rf != null) fixers.Add(rf);
                    }
                });
            } else {
                callTarget.EmitGet(cg);

                for (int i = firstArg; i < args.Count; i++) {
                    ReturnFixer rf = ReturnFixer.EmitArgument(cg, args[i]);
                    if (rf != null) fixers.Add(rf);
                }
            }

            cg.EmitCall(site.Type, "Invoke"); 

            foreach (ReturnFixer rf in fixers) {
                rf.FixReturn(cg);
            }
            cg.EmitReturnFromObject();
        }
Пример #23
0
 /// <summary>
 /// Create far JMP or CALL instruction from source address to target.
 /// </summary>
 /// <param name="sourceAddress">Address which CALL originates from rather than EIP of next instruction.</param>
 /// <param name="targetAddress">Target address to call.</param>
 /// <param name="callType">Type of instruction to assemble.</param>
 /// <returns>Byte array of assembled instruction.</returns>
 public static byte[] CreateCALL(int sourceAddress, int targetAddress, CallType callType)
 {
     int offset = targetAddress - sourceAddress - 5;
     byte[] CALL = new byte[5];
     switch (callType)
     {
         case CallType.CALL:
             CALL[0] = 0xE8;
             break;
         case CallType.JMP:
             CALL[0] = 0xE9;
             break;
     }
     CALL[1] = (byte)(offset);
     CALL[2] = (byte)(offset >> 8);
     CALL[3] = (byte)(offset >> 16);
     CALL[4] = (byte)(offset >> 24);
     return CALL;
 }
Пример #24
0
 public static OpCode[] Call(CallType call, Addr32 func, object[] args)
 {
     List<OpCode> ret = new List<OpCode>();
     args = args.Clone() as object[];
     Array.Reverse(args);
     foreach (object arg in args)
     {
         if (arg is int) ret.Add(Push((uint)(int)arg));
         else if (arg is uint) ret.Add(Push((uint)arg));
         else if (arg is Val32) ret.Add(Push((Val32)arg));
         else if (arg is Addr32) ret.Add(Push((Addr32)arg));
         else throw new Exception("Unknown argument.");
     }
     ret.Add(Call(func));
     if (call == CallType.CDecl)
     {
         ret.Add(Add(Reg32.ESP, (byte)(args.Length * 4)));
     }
     return ret.ToArray();
 }
Пример #25
0
 public Call(	String name, Activity activity, CallType type, Tone tone,
     String duration, String encoder, String decoder, long bytesSent,
     long bytesReceived, long packetLoss, long packetError, long jitter,
     long decodeLatency, long roundTripDelay)
 {
     mName = name;
     mActivity = activity;
     mType = type;
     mTone = tone;
     mDuration = duration;
     mEncoder = encoder;
     mDecoder = decoder;
     mBytesSent = bytesSent;
     mBytesReceived = bytesReceived;
     mPacketLoss = packetLoss;
     mPacketError = packetError;
     mJitter = jitter;
     mDecodeLatency = decodeLatency;
     mRoundTripDelay = roundTripDelay;
 }
Пример #26
0
        public static void HandleCall(int entityRef, CallType funcID)
        {
            var entity = Entity.GetEntity(entityRef);
            int numArgs = GameInterface.Notify_NumArgs();
            var paras = CollectParameters(numArgs);

            switch (funcID)
            {
                case CallType.StartGameType:
                    ScriptProcessor.RunAll(script => script.OnStartGameType());
                    break;
                case CallType.PlayerConnect:
                    //ScriptProcessor.RunAll(script => script.OnPlayerConnect(entity));
                    break;
                case CallType.PlayerDisconnect:
                    ScriptProcessor.RunAll(script => script.OnPlayerDisconnect(entity));
                    break;
                case CallType.PlayerDamage:
                    if (paras[6].IsNull)
                    {
                        paras[6] = new Vector3(0, 0, 0);
                    }

                    if (paras[7].IsNull)
                    {
                        paras[7] = new Vector3(0, 0, 0);
                    }

                    ScriptProcessor.RunAll(script => script.OnPlayerDamage(entity, paras[0].As<Entity>(), paras[1].As<Entity>(), paras[2].As<int>(), paras[3].As<int>(), paras[4].As<string>(), paras[5].As<string>(), paras[6].As<Vector3>(), paras[7].As<Vector3>(), paras[8].As<string>()));
                    break;
                case CallType.PlayerKilled:
                    if (paras[5].IsNull)
                    {
                        paras[5] = new Vector3(0, 0, 0);
                    }

                    ScriptProcessor.RunAll(script => script.OnPlayerKilled(entity, paras[0].As<Entity>(), paras[1].As<Entity>(), paras[2].As<int>(), paras[3].As<string>(), paras[4].As<string>(), paras[5].As<Vector3>(), paras[6].As<string>()));
                    break;
            }
        }
Пример #27
0
 public static OpCode[] CallArgs(CallType call, Addr32 func, object[] args)
 {
     var list = new ArrayList();
     for (int i = args.Length - 1; i >= 0; i--)
     {
         var arg = args[i];
         if (arg is int) list.Add(PushD(Val32.NewI((int)arg)));
         else if (arg is uint) list.Add(PushD(Val32.New((uint)arg)));
         else if (arg is Val32) list.Add(PushD((Val32)arg));
         else if (arg is Addr32) list.Add(PushA((Addr32)arg));
         else throw new Exception("Unknown argument.");
     }
     list.Add(CallA(func));
     if (call == CallType.CDecl)
     {
         list.Add(AddR(Reg32.ESP, Val32.New((byte)(args.Length * 4))));
     }
     var ret = new OpCode[list.Count];
     for (int i = 0; i < ret.Length; i++)
         ret[i] = list[i] as OpCode;
     return ret;
 }
Пример #28
0
 public CallProvider GetProvider(CallType type)
 {
     return CallProvider.Create(type, _unitOfWork, _emailHelper);
 }
Пример #29
0
 public void CallByName_ArgumentException(object instance, string methodName, CallType useCallType, object[] args)
 {
     Assert.Throws <ArgumentException>(() => Versioned.CallByName(instance, methodName, useCallType, args));
 }
Пример #30
0
 public static void LateSet(object Instance, Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, Type[] TypeArguments, bool OptimisticSet, bool RValueBase, CallType CallType)
 {
     Symbols.Container container;
     if (Arguments == null)
     {
         Arguments = Symbols.NoArguments;
     }
     if (ArgumentNames == null)
     {
         ArgumentNames = Symbols.NoArgumentNames;
     }
     if (TypeArguments == null)
     {
         TypeArguments = Symbols.NoTypeArguments;
     }
     if (Type != null)
     {
         container = new Symbols.Container(Type);
     }
     else
     {
         container = new Symbols.Container(Instance);
     }
     if (container.IsCOMObject)
     {
         try
         {
             LateBinding.InternalLateSet(Instance, ref Type, MemberName, Arguments, ArgumentNames, OptimisticSet, CallType);
             if (RValueBase && Type.IsValueType)
             {
                 throw new Exception(Utils.GetResourceString("RValueBaseForValueType", new string[] { Utils.VBFriendlyName(Type, Instance), Utils.VBFriendlyName(Type, Instance) }));
             }
         }
         catch when(?)
         {
         }
     }
     else
     {
         MemberInfo[] members = container.GetMembers(ref MemberName, true);
         if (members[0].MemberType == MemberTypes.Field)
         {
             if (TypeArguments.Length > 0)
             {
                 throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue"));
             }
             if (Arguments.Length == 1)
             {
                 if (RValueBase && container.IsValueType)
                 {
                     throw new Exception(Utils.GetResourceString("RValueBaseForValueType", new string[] { container.VBFriendlyName, container.VBFriendlyName }));
                 }
                 container.SetFieldValue((FieldInfo)members[0], Arguments[0]);
             }
             else
             {
                 LateIndexSetComplex(container.GetFieldValue((FieldInfo)members[0]), Arguments, ArgumentNames, OptimisticSet, true);
             }
         }
         else
         {
             OverloadResolution.ResolutionFailure failure;
             Symbols.Method method;
             BindingFlags   setProperty = BindingFlags.SetProperty;
             if (ArgumentNames.Length > Arguments.Length)
             {
                 throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue"));
             }
             if (TypeArguments.Length == 0)
             {
                 method = ResolveCall(container, MemberName, members, Arguments, ArgumentNames, Symbols.NoTypeArguments, setProperty, false, ref failure);
                 if (failure == OverloadResolution.ResolutionFailure.None)
                 {
                     if (RValueBase && container.IsValueType)
                     {
                         throw new Exception(Utils.GetResourceString("RValueBaseForValueType", new string[] { container.VBFriendlyName, container.VBFriendlyName }));
                     }
                     container.InvokeMethod(method, Arguments, null, setProperty);
                     return;
                 }
             }
             BindingFlags lookupFlags = BindingFlags.GetProperty | BindingFlags.InvokeMethod;
             switch (failure)
             {
             case OverloadResolution.ResolutionFailure.None:
             case OverloadResolution.ResolutionFailure.MissingMember:
                 method = ResolveCall(container, MemberName, members, Symbols.NoArguments, Symbols.NoArgumentNames, TypeArguments, lookupFlags, false, ref failure);
                 if (failure == OverloadResolution.ResolutionFailure.None)
                 {
                     object instance = container.InvokeMethod(method, Symbols.NoArguments, null, lookupFlags);
                     if (instance == null)
                     {
                         throw new MissingMemberException(Utils.GetResourceString("IntermediateLateBoundNothingResult1", new string[] { method.ToString(), container.VBFriendlyName }));
                     }
                     LateIndexSetComplex(instance, Arguments, ArgumentNames, OptimisticSet, true);
                     return;
                 }
                 break;
             }
             if (!OptimisticSet)
             {
                 if (TypeArguments.Length == 0)
                 {
                     ResolveCall(container, MemberName, members, Arguments, ArgumentNames, TypeArguments, setProperty, true, ref failure);
                 }
                 else
                 {
                     ResolveCall(container, MemberName, members, Symbols.NoArguments, Symbols.NoArgumentNames, TypeArguments, lookupFlags, true, ref failure);
                 }
                 throw new InternalErrorException();
             }
         }
     }
 }
Пример #31
0
        public static void InsertUpdateDeleteTests()
        {
            var storage = DataStorage.Instance;

            var status = false;


            /***
             * TESTING NUMBERING PLAN
             */
            var numberingPlan = new NumberingPlansDataMapper();

            var athens = "athens";
            var kaz    = "kaz";

            var plan = new NumberingPlan();

            plan.City            = athens;
            plan.Iso3CountryCode = kaz;

            var ev = new CustomExpressionVisitor();

            Expression <Func <NumberingPlan, bool> > exp1 = item => item.City.ToLower() == athens;
            Expression <Func <NumberingPlan, bool> > exp2 = (item => item.Iso3CountryCode.ToLower() == kaz);

            var data1 = numberingPlan.Get(exp1).ToList();
            var data2 = numberingPlan.Get(exp2).ToList();


            /***
             * TESTING THE SINGLETON SITES DEPARTMENTS DATA MAPPER
             */
            var allSitesDepartments = storage.SitesDepartments.GetAll();


            var newSite = new Site
            {
                CountryCode = "GRC",
                Description = "Sample Description",
                Name        = "TEST-SITE"
            };

            var newDepartment = new Department
            {
                Name        = "TEST-DEPARTMENT",
                Description = "Sample Description"
            };

            newSite.Id       = storage.Sites.Insert(newSite);
            newDepartment.Id = storage.Departments.Insert(newDepartment);

            var newSiteDepartment = new SiteDepartment
            {
                SiteId       = newSite.Id,
                DepartmentId = newDepartment.Id
            };

            newSiteDepartment.Id = storage.SitesDepartments.Insert(newSiteDepartment);

            allSitesDepartments = storage.SitesDepartments.GetAll();

            newSiteDepartment.SiteId = 29;

            status = storage.SitesDepartments.Update(newSiteDepartment);

            newSiteDepartment = storage.SitesDepartments.GetById(newSiteDepartment.Id);

            allSitesDepartments = storage.SitesDepartments.GetAll();

            status = storage.SitesDepartments.Delete(newSiteDepartment);

            status = storage.Departments.Delete(newDepartment);

            status = storage.Sites.Delete(newSite);


            /***
             * TESTING USERS DATA MAPPER
             */
            var allUsers = storage.Users.GetAll();

            var newUser = new User
            {
                EmployeeId      = 99887766,
                SipAccount      = "*****@*****.**",
                FullName        = "UNKNOWN SAMPLE USER",
                DisplayName     = "UNKNOWN USER",
                SiteName        = "MOA",
                DepartmentName  = "ISD",
                NotifyUser      = "******",
                TelephoneNumber = "12334545667",
                UpdatedAt       = DateTime.MinValue,
                //UpdatedByAD = 1,
                CreatedAt = DateTime.Now
            };

            storage.Users.Insert(newUser);

            newUser = storage.Users.GetBySipAccount(newUser.SipAccount);

            newUser.DisplayName = "UNKNOWN";

            status = storage.Users.Update(newUser);
            status = storage.Users.Delete(newUser);


            /***
             * TESTING SYSTEM ROLES
             */
            var developerRole = storage.Roles.GetByRoleId(10);

            var systemRole = new SystemRole
            {
                Description = "TESTING SYSTEM ROLE",
                RoleId      = developerRole.RoleId,
                SipAccount  = "*****@*****.**",
                SiteId      = 29
            };

            systemRole.Id = storage.SystemRoles.Insert(systemRole);

            systemRole = storage.SystemRoles.GetById(systemRole.Id);

            systemRole.SiteId = 31;

            status = storage.SystemRoles.Update(systemRole);

            systemRole = storage.SystemRoles.GetById(systemRole.Id);

            status = storage.SystemRoles.Delete(systemRole);


            /***
             * TESTING SITES DEPARTMENTS DATA MAPPER
             */
            var moaSite       = storage.Sites.GetById(29);
            var rasoSite      = storage.Sites.GetById(31);
            var isdDepartment = storage.Departments.GetByName("ISD");

            var siteDepartment = new SiteDepartment
            {
                SiteId       = moaSite.Id,
                DepartmentId = isdDepartment.Id
            };

            siteDepartment.Id = storage.SitesDepartments.Insert(siteDepartment);

            siteDepartment = storage.SitesDepartments.GetById(siteDepartment.Id);

            siteDepartment.SiteId = rasoSite.Id;

            status = storage.SitesDepartments.Update(siteDepartment);

            siteDepartment = storage.SitesDepartments.GetById(siteDepartment.Id);

            status = storage.SitesDepartments.Delete(siteDepartment);


            /***
             * TESTING SITES DATA MAPPER
             */
            var site = new Site
            {
                CountryCode = "GRC",
                Description = "SAMPLE GREECE SITE",
                Name        = "SAMPLE SITE"
            };

            site.Id = storage.Sites.Insert(site);

            site = storage.Sites.GetById(site.Id);

            site.Name = "sample sample site";

            status = storage.Sites.Update(site);
            status = storage.Sites.Delete(site);


            /***
             * TESTING ROLES DATA MAPPER
             */
            var role123 = new Role
            {
                RoleDescription = "SAMPLE ROLE",
                RoleId          = 123123,
                RoleName        = "SAMPLE-01"
            };

            role123.Id = storage.Roles.Insert(role123);

            role123.RoleName = "sample-02.01";

            status = storage.Roles.Update(role123);
            status = storage.Roles.Delete(role123);


            /***
             * TESTING NGN RATES DATA MAPPER
             */
            var ngnRate = new RateForNgn
            {
                DialingCodeId = 1,
                Rate          = Convert.ToDecimal(15.45)
            };

            ngnRate.Id = 19; //_STORAGE.RatesForNGN.Insert(NGNRate, 10);

            ngnRate = storage.RatesForNgn.GetByGatewayId(10).Find(rate => rate.Id == 19);

            ngnRate.Rate = Convert.ToDecimal(20.45);

            status = storage.RatesForNgn.Update(ngnRate, 10);
            status = storage.RatesForNgn.Delete(ngnRate, 10);


            /***
             * TESTING POOLS DATA MAPPER
             */
            var newPool = new Pool
            {
                Fqdn = "TESTING POOL FQDN"
            };

            newPool.Id = storage.Pools.Insert(newPool);

            newPool.Fqdn = "CHANGED FQDN";

            status = storage.Pools.Update(newPool);
            status = storage.Pools.Delete(newPool);


            /***
             * TESTING PHONE CALLS EXCLUSIONS
             */
            var exclusion = new PhoneCallExclusion
            {
                ExclusionSubject = "*****@*****.**",
                Description      = "SAMPLE EXCLUSION TEST",
                ExclusionType    = Globals.PhoneCallExclusion.Type.Source.Value(),
                SiteId           = 29,
                ZeroCost         = Globals.PhoneCallExclusion.ZeroCost.No.Value(),
                AutoMark         = Globals.PhoneCallExclusion.AutoMark.Business.Value()
            };

            exclusion.Id = storage.PhoneCallsExclusions.Insert(exclusion);

            exclusion = storage.PhoneCallsExclusions.GetById(789);

            exclusion.AutoMark = "";
            exclusion.ZeroCost = Globals.PhoneCallExclusion.ZeroCost.Yes.Value();

            status = storage.PhoneCallsExclusions.Update(exclusion);
            status = storage.PhoneCallsExclusions.Delete(exclusion);


            /***
             * TESTING PHONE BOOK CONTACTS DATA MAPPER
             */
            var contact = new PhoneBookContact
            {
                DestinationCountry = "JOR",
                DestinationNumber  = "123123123123123123",
                Name       = "SAMPLE CONTACT",
                SipAccount = "*****@*****.**",
                Type       = "Personal"
            };

            contact.Id = storage.PhoneBooks.Insert(contact);

            var allContacts = storage.PhoneBooks.GetBySipAccount(contact.SipAccount);

            contact.Name = "SAMPLE PHONE BOOK CONTANCT NAME";
            contact.Type = "Business";

            status = storage.PhoneBooks.Update(contact);
            status = storage.PhoneBooks.Delete(contact);


            /***
             * TESTING NUMBERING PLAN FOR NGN
             */
            var ngn = new NumberingPlanForNgn
            {
                Description     = "TEST NGN",
                DialingCode     = "8000000000000",
                Iso3CountryCode = "GRC",
                TypeOfServiceId = 6,
                Provider        = "SAMPLE PROVIDER"
            };

            ngn.Id = storage.NumberingPlansForNgn.Insert(ngn);

            ngn = storage.NumberingPlansForNgn.GetById(ngn.Id);

            ngn.Description = "TEST NGN - UPDATED.";

            status = storage.NumberingPlansForNgn.Update(ngn);
            status = storage.NumberingPlansForNgn.Delete(ngn);


            /***
             * TESTING NUMBER PLAN DATA MAPPER
             */
            var numPlan = new NumberingPlan
            {
                City            = "Xin Che Bang",
                CountryName     = "ChinaYaNa",
                DialingPrefix   = 90909,
                Iso2CountryCode = "CY",
                Iso3CountryCode = "CYN",
                Provider        = string.Empty,
                TypeOfService   = "countrycode"
            };

            storage.NumberingPlans.Insert(numPlan);

            numPlan.CountryName = "ChynaYaNa";

            status = storage.NumberingPlans.Update(numPlan);
            status = storage.NumberingPlans.Delete(numPlan);


            /***
             * TESTING MONITORING SERVERS INFO DATA MAPPER
             */
            var monServer = new MonitoringServerInfo
            {
                CreatedAt             = DateTime.Now,
                DatabaseName          = "asdasdasd",
                Description           = "TESTING MONITORING SERVER",
                InstanceHostName      = "SAMPL INSTANCE HOST NAME",
                InstanceName          = "SAMPLE HOST NAME",
                Password              = "******",
                PhoneCallsTable       = "PhoneCalls2012310123",
                TelephonySolutionName = "Lync123124123",
                Username              = "******"
            };

            monServer.Id = storage.MonitoringServers.Insert(monServer);

            monServer.Username = monServer.Username.ToLower();
            monServer.Password = "******";

            status = storage.MonitoringServers.Update(monServer);
            status = storage.MonitoringServers.Delete(monServer);


            /***
             * TESTING MAIL TAMPLEATES DATA MAPPER
             */
            var newTemplate = new MailTemplate
            {
                TemplateBody = "SAMPLE",
                Subject      = "SAMPLE"
            };

            newTemplate.Id = storage.MailTemplates.Insert(newTemplate);

            newTemplate.Subject      = "TESTING TEMPLATE";
            newTemplate.TemplateBody = "TESTING TEMPLATE BODY TEXT";

            status = storage.MailTemplates.Update(newTemplate);
            status = storage.MailTemplates.Delete(newTemplate);


            /***
             * TESTING GATEWAYS RATES DATA MAPPER
             */
            var gatewayRateInfo = new GatewayRate
            {
                CurrencyCode      = "EUR",
                StartingDate      = DateTime.Now,
                EndingDate        = DateTime.MinValue,
                RatesTableName    = null,
                NgnRatesTableName = null,
                ProviderName      = "SAMPLE PROVIDER",
                GatewayId         = 10
            };

            gatewayRateInfo.Id = storage.GatewaysRates.Insert(gatewayRateInfo);

            gatewayRateInfo = storage.GatewaysRates.GetById(gatewayRateInfo.Id);

            gatewayRateInfo.CurrencyCode = "USD";

            status = storage.GatewaysRates.Update(gatewayRateInfo);
            status = storage.GatewaysRates.Delete(gatewayRateInfo);


            /***
             * TESTING GATEWAYS INFO DATA MAPPER
             */
            var sampleGateway = new Gateway
            {
                Name = "SAMPLE GATEWAY"
            };

            sampleGateway.Id = storage.Gateways.Insert(sampleGateway);

            var newGatewayInfo = new GatewayInfo
            {
                Description = "New Info for Gateway",
                GatewayId   = sampleGateway.Id,
                PoolId      = 2,
                SiteId      = 29
            };

            storage.GatewaysInfo.Insert(newGatewayInfo);

            var allGatewayInfo = storage.GatewaysInfo.GetByGatewayId(newGatewayInfo.GatewayId).ToList();

            newGatewayInfo.Description = "Info For Gateway - UPDATED.";

            status = storage.GatewaysInfo.Update(newGatewayInfo);
            status = storage.GatewaysInfo.Delete(newGatewayInfo);
            status = storage.Gateways.Delete(sampleGateway);


            /***
             * TESTING GATEWAYS DATA MAPPER
             */
            var newGateway = new Gateway
            {
                Name = "Sameer"
            };

            newGateway.Id = storage.Gateways.Insert(newGateway);

            newGateway.Name = "Sameer-02";

            status = storage.Gateways.Update(newGateway);
            status = storage.Gateways.Delete(newGateway);


            /***
             * TESTING DIDs DATA MAPPER
             */
            var newDid = new Did
            {
                Description = "SAMPLE DID",
                Regex       = "SAMPLE REGEX",
                SiteId      = 29
            };

            newDid.Id = storage.DiDs.Insert(newDid);

            newDid = storage.DiDs.GetById(newDid.Id);

            newDid.Description = "SAMPLE DID - UPDATED DESCRIPTION";

            status = storage.DiDs.Update(newDid);
            status = storage.DiDs.Delete(newDid);


            /***
             * TESTING DEPARTMENTS
             */
            var department = new Department
            {
                Name        = "SUMURMUR",
                Description = "Sumurmur Department"
            };

            department.Id = storage.Departments.Insert(department);

            department = storage.Departments.GetById(department.Id);

            department.Description = "Never mind!";

            status = storage.Departments.Update(department);
            status = storage.Departments.Delete(department);


            /***
             * TESTING DEPARTMENT HEAD ROLES
             */
            var moa     = storage.Sites.GetById(29);
            var moaIsd  = storage.SitesDepartments.GetBySiteId(29).ToList().Find(item => item.Department.Name == "ISD");
            var depHead = new DepartmentHeadRole
            {
                SipAccount       = "*****@*****.**",
                SiteDepartmentId = moaIsd.Id
            };

            depHead.Id = storage.DepartmentHeads.Insert(depHead);

            depHead = storage.DepartmentHeads.GetById(depHead.Id);

            depHead.SipAccount = "*****@*****.**";

            status = storage.DepartmentHeads.Update(depHead);
            status = storage.DepartmentHeads.Delete(depHead);


            /***
             * TESTING DELEGATE ROLES DATA MAPPER
             */
            moa    = storage.Sites.GetById(29);
            moaIsd = storage.SitesDepartments.GetBySiteId(29).ToList().Find(item => item.Department.Name == "ISD");

            var userDelegate = new DelegateRole
            {
                DelegationType        = 3,
                DelegeeSipAccount     = "*****@*****.**",
                ManagedUserSipAccount = "*****@*****.**"
            };

            var departmentDelegate = new DelegateRole
            {
                DelegationType          = 2,
                DelegeeSipAccount       = "*****@*****.**",
                ManagedSiteDepartmentId = moaIsd.Id
            };

            var siteDelegate = new DelegateRole
            {
                DelegationType    = 1,
                DelegeeSipAccount = "*****@*****.**",
                ManagedSiteId     = moa.Id
            };

            userDelegate.Id       = storage.DelegateRoles.Insert(userDelegate);
            departmentDelegate.Id = storage.DelegateRoles.Insert(departmentDelegate);
            siteDelegate.Id       = storage.DelegateRoles.Insert(siteDelegate);

            var allRoles = storage.DelegateRoles.GetByDelegeeSipAccount(userDelegate.DelegeeSipAccount);

            userDelegate.DelegeeSipAccount       = "*****@*****.**";
            departmentDelegate.DelegeeSipAccount = "*****@*****.**";
            siteDelegate.DelegeeSipAccount       = "*****@*****.**";

            status = storage.DelegateRoles.Update(userDelegate);
            status = storage.DelegateRoles.Update(departmentDelegate);
            status = storage.DelegateRoles.Update(siteDelegate);

            allRoles = storage.DelegateRoles.GetByDelegeeSipAccount(userDelegate.DelegeeSipAccount);

            status = storage.DelegateRoles.Delete(userDelegate);
            status = storage.DelegateRoles.Delete(departmentDelegate);
            status = storage.DelegateRoles.Delete(siteDelegate);


            /***
             * TESTING Currencies DATA MAPPER
             */
            var newCurrency = new Currency
            {
                Iso3Code = "ZVZ",
                Name     = "ZeeVeeZee"
            };

            newCurrency.Id   = storage.Currencies.Insert(newCurrency);
            newCurrency.Name = "ZeeeeVeZe";
            status           = storage.Currencies.Update(newCurrency);
            status           = storage.Currencies.Delete(newCurrency);


            /***
             * TESTING COUNTRIES DATA MAPPER
             */
            var euro       = storage.Currencies.GetByIso3Code("EUR");
            var newCountry = new Country
            {
                CurrencyId = euro.Id,
                Iso2Code   = "ZZ",
                Iso3Code   = "ZVZ",
                Name       = "ZeeVeeZee"
            };

            newCountry.Id       = storage.Countries.Insert(newCountry);
            newCountry          = storage.Countries.GetById(newCountry.Id);
            newCountry.Iso3Code = "VVZ";
            newCountry.Name     = "VeeVeeZee";
            status = storage.Countries.Update(newCountry);
            status = storage.Countries.Delete(newCountry);


            /***
             * TESTING CALL TYPES DATA MAPPER
             */
            var newCallType = new CallType
            {
                Description = "Testing call types data mapper.",
                Name        = "TEST-CALL-TYPE",
                TypeId      = 2345123
            };

            newCallType.Id = storage.CallTypes.Insert(newCallType);

            newCallType.Description = newCallType.Description.ToUpper();
            newCallType.Name        = (newCallType.Name + "-02").ToUpper();

            status = storage.CallTypes.Update(newCallType);
            status = storage.CallTypes.Delete(newCallType);


            /***
             * TESTING CALL MARKER STATUS DATA MAPPER
             */
            var newMarkerStatus = new CallMarkerStatus
            {
                PhoneCallsTable = "PhoneCalls2015",
                Timestamp       = DateTime.Now,
                Type            = Globals.CallMarkerStatus.Type.CallsMarking.Value()
            };

            newMarkerStatus.Id = storage.CallMarkers.Insert(newMarkerStatus);

            newMarkerStatus.Type      = Globals.CallMarkerStatus.Type.ApplyingRates.Value();
            newMarkerStatus.Timestamp = DateTime.Now;

            status = storage.CallMarkers.Update(newMarkerStatus);
            status = storage.CallMarkers.Delete(newMarkerStatus);


            /***
             * TESTING BUNDLED ACCOUNTS
             */
            var bundled1 = new BundledAccount
            {
                PrimarySipAccount    = "*****@*****.**",
                AssociatedSipAccount = "*****@*****.**"
            };

            var bundled2 = new BundledAccount
            {
                PrimarySipAccount    = "*****@*****.**",
                AssociatedSipAccount = "*****@*****.**"
            };

            bundled1.Id = storage.BundledAccounts.Insert(bundled1);
            bundled2.Id = storage.BundledAccounts.Insert(bundled2);

            var allBundled     = storage.BundledAccounts.GetAll();
            var aalhourBundled = storage.BundledAccounts.GetAssociatedSipAccounts("*****@*****.**");

            bundled2.AssociatedSipAccount = "*****@*****.**";

            status = storage.BundledAccounts.Update(bundled2);
            status = storage.BundledAccounts.Delete(bundled1);
            status = storage.BundledAccounts.Delete(bundled2);


            /***
             * TESTING ANNOUNCEMENTS
             */
            var ann = new Announcement
            {
                ForRole          = 10,
                ForSite          = 29,
                PublishOn        = DateTime.Now,
                AnnouncementBody = "Hello Developer."
            };

            ann.Id = storage.Announcements.Insert(ann);

            ann = storage.Announcements.GetById(ann.Id);

            ann.AnnouncementBody = "Hello Developer. Things have changed.";

            status = storage.Announcements.Update(ann);
            status = storage.Announcements.Delete(ann);
        }
Пример #32
0
 public static Call First(this IEnumerable <Call> calls, CallType type, Suit suit, Side side)
 {
     return(calls.FirstOrDefault(c => c.CallType == type &&
                                 (c.CallType != CallType.Bid || c.Bid.Suit == suit) &&
                                 c.Bidder.GetSide() == side));
 }
Пример #33
0
        // (clr-call type member obj arg1 ... )
        public override Expression Generate(object args, CodeBlock cb)
        {
            Type   t        = null;
            string type     = null;
            bool   inferred = false;

            object rtype = Builtins.First(args);

            ExtractTypeInfo(rtype, out t, out type, out inferred);

            string member = null;
            var    marg   = Builtins.Second(args);

            object memobj = null;

            Type[] argtypes = null;
            Type[] gentypes = null;

            if (marg is SymbolId)
            {
                var mem = Builtins.SymbolValue(marg);

                if (mem is Cons)
                {
                    ExtractMethodInfo(mem as Cons, out member, ref argtypes, ref gentypes);
                }
                else
                {
                    ClrSyntaxError("clr-call", "type member not supported", mem);
                }
            }
            else
            {
                memobj = Builtins.Second(marg);

                member = memobj is SymbolId?SymbolTable.IdToString((SymbolId)memobj) : "";

                if (memobj is string)
                {
                    string mems = memobj as string;
                    int    bi   = mems.IndexOf('(');
                    if (bi < 0)
                    {
                        member = mems;
                    }
                    else
                    {
                        member = mems.Substring(0, bi);
                    }
                }
                else if (memobj is Cons)
                {
                    ExtractMethodInfo(memobj as Cons, out member, ref argtypes, ref gentypes);
                }
            }

            Expression instance = GetAst(Builtins.Third(args), cb);

            CallType ct = CallType.ImplicitInstance;

            if (instance is ConstantExpression && ((ConstantExpression)instance).Value == null)
            {
                ct = CallType.None;

                if (inferred)
                {
                    ClrSyntaxError("clr-call", "type inference not possible on static member", member);
                }
            }
            else if (inferred)
            {
                if (instance is UnaryExpression && instance.Type == typeof(object))
                {
                    var ue = (UnaryExpression)instance;
                    instance = ue.Operand;
                }
                t = instance.Type;
            }
            else
            {
                instance = ConvertToHelper(t, instance);
            }

            type = t.Name;

            Expression[] arguments = GetAstListNoCast(Cdddr(args) as Cons, cb);

            if (member == "get_Item")
            {
                if (Attribute.IsDefined(t, typeof(DefaultMemberAttribute)))
                {
                    var dma = Attribute.GetCustomAttribute(t, typeof(DefaultMemberAttribute)) as DefaultMemberAttribute;
                    member = "get_" + dma.MemberName;
                }
                else if (t.IsArray)
                {
                    var index = arguments[0];
                    return(Ast.ArrayIndex(instance, Ast.ConvertHelper(index, typeof(int))));
                }
            }
            else if (member == "set_Item")
            {
                if (Attribute.IsDefined(t, typeof(DefaultMemberAttribute)))
                {
                    var dma = Attribute.GetCustomAttribute(t, typeof(DefaultMemberAttribute)) as DefaultMemberAttribute;
                    member = "set_" + dma.MemberName;
                }
                else if (t.IsArray)
                {
                    var index = arguments[0];
                    var v     = arguments[1];
                    return(Ast.Comma(Ast.AssignArrayIndex(instance, Ast.ConvertHelper(index, typeof(int)), v), Ast.ReadField(null, Unspecified)));
                }
            }

            List <MethodBase> candidates = new List <MethodBase>();

            BindingFlags bf = BindingFlags.Public | (ct == CallType.None ? BindingFlags.Static : BindingFlags.Instance) | BindingFlags.FlattenHierarchy;

            foreach (MethodInfo mi in t.GetMember(member, MemberTypes.Method, bf))
            {
                if (PAL.ExcludeParamtypes(mi))
                {
                    continue;
                }
                if (mi.ContainsGenericParameters)
                {
                    if (gentypes != null && mi.GetGenericArguments().Length == gentypes.Length)
                    {
                        candidates.Add(mi.MakeGenericMethod(gentypes));
                        continue;
                    }
                }
                candidates.Add(mi);
            }

            Type[] types = new Type[arguments.Length];

            for (int i = 0; i < types.Length; i++)
            {
                types[i] = arguments[i].Type;
            }

            if (memobj is string)
            {
                string mems = memobj as string;
                int    bi   = mems.IndexOf('(');
                if (bi < 0)
                {
                    // do notthig
                }
                else
                {
                    string[] typeargs = mems.Substring(bi + 1).TrimEnd(')').Split(',');

                    for (int i = 0; i < types.Length; i++)
                    {
                        if (typeargs[i].Length > 0)
                        {
                            types[i] = ScanForType(typeargs[i]);
                        }
                    }
                }
            }
            else if (argtypes != null)
            {
                for (int i = 0; i < types.Length; i++)
                {
                    types[i] = argtypes[i];
                }
            }

            if (ct == CallType.ImplicitInstance)
            {
                types = ArrayUtils.Insert(t, types);
            }

            MethodBinder mb = MethodBinder.MakeBinder(Binder, member, candidates, BinderType.Normal);

            MethodCandidate mc = mb.MakeBindingTarget(ct, types);

            if (mc == null)
            {
                types = new Type[arguments.Length];

                for (int i = 0; i < types.Length; i++)
                {
                    types[i] = typeof(object);
                }

                if (ct == CallType.ImplicitInstance)
                {
                    types = ArrayUtils.Insert(t, types);
                }

                mc = mb.MakeBindingTarget(ct, types);
            }

            if (mc != null)
            {
                MethodInfo meth = (MethodInfo)mc.Target.Method;
                // do implicit cast
                ParameterInfo[] pars = meth.GetParameters();
                for (int i = 0; i < arguments.Length; i++)
                {
                    Type tt = pars[i].ParameterType;
                    arguments[i] = ConvertToHelper(tt, arguments[i]);
                }

                Expression r = null;

                // o god...
                if (ct == CallType.ImplicitInstance)
                {
                    r = Ast.ComplexCallHelper(instance, (MethodInfo)mc.Target.Method, arguments);
                }
                else
                {
                    r = Ast.ComplexCallHelper((MethodInfo)mc.Target.Method, arguments);
                }

                return(ConvertFromHelper(meth.ReturnType, r));
            }

            ClrSyntaxError("clr-call", "member could not be resolved on type: " + type, args, member);

            return(null);
        }
Пример #34
0
        private static Action <MethodVariables, Stack <Expression>, Instruction, SyntaxGraphNode> Call(CallType callType)
        {
            return((variables, stack, instruction, node) =>
            {
                var targetMethod = (MethodReference)instruction.Operand;

                // Pop the arguments, in reverse order
                var arguments = new List <Expression>(targetMethod.Parameters.Count);
                for (var i = 0; i < targetMethod.Parameters.Count; i++)
                {
                    var expr = Pop(stack);
                    arguments.Insert(0, expr);
                }

                // Pop the object reference
                var target = targetMethod.HasThis && callType != CallType.Constructor ?
                             Pop(stack) :
                             null;

                // Create the call expression
                var call = new CallExpression(targetMethod, callType, target, arguments, instruction);

                // Determine if this should go on the stack
                if (callType != CallType.Constructor && targetMethod.ReturnType.FullName.Equals("System.Void"))
                {
                    // It's a statement
                    node.AddStatement(new ExpressionStatement(call, instruction));
                }
                else
                {
                    // It's an expression
                    stack.Push(call);
                }
            });
        }
Пример #35
0
 private Exception NoApplicableTarget(CallType callType, Type[] types)
 {
     return(new ArgumentTypeException(NoApplicableTargetMessage(callType, types)));
 }
Пример #36
0
 private static bool IsBest(MethodCandidate candidate, List <MethodCandidate> applicableTargets, CallType callType, Type[] actualTypes)
 {
     foreach (MethodCandidate target in applicableTargets)
     {
         if (candidate == target)
         {
             continue;
         }
         if (candidate.CompareTo(target, callType, actualTypes) != +1)
         {
             return(false);
         }
     }
     return(true);
 }
Пример #37
0
 private List <MethodCandidate> FindTarget(CallType callType, object[] args, SymbolId[] names)
 {
     return(SelectTargets(callType, CompilerHelpers.GetTypes(args), names));
 }
Пример #38
0
        private object CallFailed(CodeContext context, List <MethodCandidate> targets, CallType callType, object[] args)
        {
            if (_binder.IsBinaryOperator)
            {
                return(context.LanguageContext.GetNotImplemented(targets.ToArray()));
            }

            if (targets.Count == 0)
            {
                throw NoApplicableTarget(callType, CompilerHelpers.GetTypes(args));
            }
            else
            {
                throw MultipleTargets(targets, callType, CompilerHelpers.GetTypes(args));
            }
        }
Пример #39
0
        /* this is called from unmanaged code */
        internal static object PrivateInvoke(RealProxy rp, IMessage msg, out Exception exc,
                                             out object [] out_args)
        {
            MonoMethodMessage mMsg = (MonoMethodMessage)msg;

            mMsg.LogicalCallContext = CallContext.CreateLogicalCallContext(true);
            CallType call_type   = mMsg.CallType;
            bool     is_remproxy = (rp is RemotingProxy);

            out_args = null;
            IMethodReturnMessage res_msg = null;

            if (call_type == CallType.BeginInvoke)
            {
                // todo: set CallMessage in runtime instead
                mMsg.AsyncResult.CallMessage = mMsg;
            }

            if (call_type == CallType.EndInvoke)
            {
                res_msg = (IMethodReturnMessage)mMsg.AsyncResult.EndInvoke();
            }

            // Check for constructor msg
            if (mMsg.MethodBase.IsConstructor)
            {
                if (is_remproxy)
                {
                    res_msg = (IMethodReturnMessage)(rp as RemotingProxy).ActivateRemoteObject((IMethodMessage)msg);
                }
                else
                {
                    msg = new ConstructionCall(rp.GetProxiedType());
                }
            }

            if (null == res_msg)
            {
                bool failed = false;

                try {
                    res_msg = (IMethodReturnMessage)rp.Invoke(msg);
                } catch (Exception ex) {
                    failed = true;
                    if (call_type == CallType.BeginInvoke)
                    {
                        // If async dispatch crashes, don't propagate the exception.
                        // The exception will be raised when calling EndInvoke.
                        mMsg.AsyncResult.SyncProcessMessage(new ReturnMessage(ex, msg as IMethodCallMessage));
                        res_msg = new ReturnMessage(null, null, 0, null, msg as IMethodCallMessage);
                    }
                    else
                    {
                        throw;
                    }
                }

                // Note, from begining this code used AsyncResult.IsCompleted for
                // checking if it was a remoting or custom proxy, but in some
                // cases the remoting proxy finish before the call returns
                // causing this method to be called, therefore causing all kind of bugs.
                if ((!is_remproxy) && call_type == CallType.BeginInvoke && !failed)
                {
                    IMessage asyncMsg = null;

                    // allow calltype EndInvoke to finish
                    asyncMsg = mMsg.AsyncResult.SyncProcessMessage(res_msg as IMessage);
                    out_args = res_msg.OutArgs;
                    res_msg  = new ReturnMessage(asyncMsg, null, 0, null, res_msg as IMethodCallMessage);
                }
            }

            if (res_msg.LogicalCallContext != null && res_msg.LogicalCallContext.HasInfo)
            {
                CallContext.UpdateCurrentCallContext(res_msg.LogicalCallContext);
            }

            exc = res_msg.Exception;

            // todo: remove throw exception from the runtime invoke
            if (null != exc)
            {
                out_args = null;
                throw exc.FixRemotingException();
            }
            else if (res_msg is IConstructionReturnMessage)
            {
                if (out_args == null)
                {
                    out_args = res_msg.OutArgs;
                }
            }
            else if (mMsg.CallType == CallType.BeginInvoke)
            {
                // We don't have OutArgs in this case.
            }
            else if (mMsg.CallType == CallType.Sync)
            {
                out_args = ProcessResponse(res_msg, mMsg);
            }
            else if (mMsg.CallType == CallType.EndInvoke)
            {
                out_args = ProcessResponse(res_msg, mMsg.AsyncResult.CallMessage);
            }
            else
            {
                if (out_args == null)
                {
                    out_args = res_msg.OutArgs;
                }
            }

            return(res_msg.ReturnValue);
        }
Пример #40
0
        private void PrivateInvoke(ref MessageData msgData, int type)
        {
            IMessage      message1      = (IMessage)null;
            CallType      callType      = (CallType)type;
            IMessage      message2      = (IMessage)null;
            int           msgFlags      = -1;
            RemotingProxy remotingProxy = (RemotingProxy)null;

            if (CallType.MethodCall == callType)
            {
                Message     message3 = new Message();
                MessageData msgData1 = msgData;
                message3.InitFields(msgData1);
                message1 = (IMessage)message3;
                msgFlags = message3.GetCallType();
            }
            else if (CallType.ConstructorCall == callType)
            {
                msgFlags      = 0;
                remotingProxy = this as RemotingProxy;
                bool flag = false;
                ConstructorCallMessage constructorCallMessage1;
                if (!this.IsRemotingProxy())
                {
                    constructorCallMessage1 = new ConstructorCallMessage((object[])null, (object[])null, (object[])null, (RuntimeType)this.GetProxiedType());
                }
                else
                {
                    constructorCallMessage1 = remotingProxy.ConstructorMessage;
                    Identity identityObject = remotingProxy.IdentityObject;
                    if (identityObject != null)
                    {
                        flag = identityObject.IsWellKnown();
                    }
                }
                if (constructorCallMessage1 == null | flag)
                {
                    ConstructorCallMessage constructorCallMessage2 = new ConstructorCallMessage((object[])null, (object[])null, (object[])null, (RuntimeType)this.GetProxiedType());
                    constructorCallMessage2.SetFrame(msgData);
                    message1 = (IMessage)constructorCallMessage2;
                    if (flag)
                    {
                        remotingProxy.ConstructorMessage = (ConstructorCallMessage)null;
                        if (constructorCallMessage2.ArgCount != 0)
                        {
                            throw new RemotingException(Environment.GetResourceString("Remoting_Activation_WellKnownCTOR"));
                        }
                    }
                    message2 = (IMessage) new ConstructorReturnMessage((MarshalByRefObject)this.GetTransparentProxy(), (object[])null, 0, (LogicalCallContext)null, (IConstructionCallMessage)constructorCallMessage2);
                }
                else
                {
                    constructorCallMessage1.SetFrame(msgData);
                    message1 = (IMessage)constructorCallMessage1;
                }
            }
            ChannelServices.IncrementRemoteCalls();
            if (!this.IsRemotingProxy() && (msgFlags & 2) == 2)
            {
                message2 = RealProxy.EndInvokeHelper(message1 as Message, true);
            }
            if (message2 == null)
            {
                Thread             currentThread      = Thread.CurrentThread;
                LogicalCallContext logicalCallContext = currentThread.GetMutableExecutionContext().LogicalCallContext;
                this.SetCallContextInMessage(message1, msgFlags, logicalCallContext);
                logicalCallContext.PropagateOutgoingHeadersToMessage(message1);
                message2 = this.Invoke(message1);
                this.ReturnCallContextToThread(currentThread, message2, msgFlags, logicalCallContext);
                Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext.PropagateIncomingHeadersToCallContext(message2);
            }
            if (!this.IsRemotingProxy() && (msgFlags & 1) == 1)
            {
                Message     m           = message1 as Message;
                AsyncResult asyncResult = new AsyncResult(m);
                IMessage    msg         = message2;
                asyncResult.SyncProcessMessage(msg);
                // ISSUE: variable of the null type
                __Null local1       = null;
                int    outArgsCount = 0;
                // ISSUE: variable of the null type
                __Null  local2   = null;
                Message message3 = m;
                message2 = (IMessage) new ReturnMessage((object)asyncResult, (object[])local1, outArgsCount, (LogicalCallContext)local2, (IMethodCallMessage)message3);
            }
            RealProxy.HandleReturnMessage(message1, message2);
            if (CallType.ConstructorCall != callType)
            {
                return;
            }
            IConstructionReturnMessage constructionReturnMessage = message2 as IConstructionReturnMessage;

            if (constructionReturnMessage == null)
            {
                throw new RemotingException(Environment.GetResourceString("Remoting_Proxy_BadReturnTypeForActivation"));
            }
            ConstructorReturnMessage constructorReturnMessage = constructionReturnMessage as ConstructorReturnMessage;
            MarshalByRefObject       marshalByRefObject;

            if (constructorReturnMessage != null)
            {
                marshalByRefObject = (MarshalByRefObject)constructorReturnMessage.GetObject();
                if (marshalByRefObject == null)
                {
                    throw new RemotingException(Environment.GetResourceString("Remoting_Activation_NullReturnValue"));
                }
            }
            else
            {
                marshalByRefObject = (MarshalByRefObject)RemotingServices.InternalUnmarshal((ObjRef)constructionReturnMessage.ReturnValue, this.GetTransparentProxy(), true);
                if (marshalByRefObject == null)
                {
                    throw new RemotingException(Environment.GetResourceString("Remoting_Activation_NullFromInternalUnmarshal"));
                }
            }
            if (marshalByRefObject != (MarshalByRefObject)this.GetTransparentProxy())
            {
                throw new RemotingException(Environment.GetResourceString("Remoting_Activation_InconsistentState"));
            }
            if (!this.IsRemotingProxy())
            {
                return;
            }
            remotingProxy.ConstructorMessage = (ConstructorCallMessage)null;
        }
Пример #41
0
 public void CallByName_MissingMemberException(object instance, string methodName, CallType useCallType, object[] args)
 {
     Assert.Throws <MissingMemberException>(() => Interaction.CallByName(instance, methodName, useCallType, args));
 }
        private void Dial(CallType callType, bool dialIP)
        {
            if (SelectedLine == null)
                return;

            if (!SelectedLine.RegState.IsRegistered())
            {
                MessageBox.Show("Cannot start calls while the selected line is not registered.");
                return;
            }

            if (!dialIP)
                Model.Dial(DialNumber, callType);
            else
                Model.DialIP(DialNumber, callType);

            DialNumber = string.Empty;
        }
 /// <inheritdoc />
 public TResult CustomRequest <TResult, TData>(TData data, string uri, HttpMethod method, CallType callType,
                                               RequestOptions requestOptions = null)
     where TResult : class
     where TData : class =>
 AsyncHelper.RunSync(() => CustomRequestAsync <TResult, TData>(data, uri, method, callType, requestOptions));
Пример #44
0
 private Exception MultipleTargets(List <MethodCandidate> applicableTargets, CallType callType, Type[] types)
 {
     return(new ArgumentTypeException(MultipleTargetsMessage(applicableTargets, callType, types)));
 }
Пример #45
0
        /// <summary>
        /// Constructor for the PhoneRecording class - this sets up the phone connection, dials the phone and waits for it to
        /// connect or fail.  Only if the call completes and the connection is established does this construtor complete without
        /// throwing an exception.
        /// </summary>
        /// <param name="pConnectionServer">
        /// The Connection server to have call your phone.
        /// </param>
        /// <param name="pPhoneNumberToDial">
        /// The phone number to dial
        /// </param>
        /// <param name="pRings">
        /// The number of rings to wait for - defaults to 4
        /// </param>
        /// <param name="pCallType">
        /// In Connection 10.5.2 and later video recording and playback is possible if the system is configured properly.  Defaults
        /// to audio only
        /// </param>
        public PhoneRecording(ConnectionServerRest pConnectionServer, string pPhoneNumberToDial, int pRings = 4, CallType pCallType = CallType.Audio)
        {
            if (pConnectionServer == null)
            {
                throw new ArgumentException("Null Connection Server passed to the PhoneRecording constructor");
            }

            if (string.IsNullOrEmpty(pPhoneNumberToDial))
            {
                throw new ArgumentException("Empty phone number passed the PhoneRecording constructor");
            }

            _homeServer  = pConnectionServer;
            _phoneNumber = pPhoneNumberToDial;
            _callType    = pCallType;
            _rings       = pRings;

            WebCallResult res      = AttachToPhone();
            int           iCounter = 0;

            if (res.Success)
            {
                Thread.Sleep(200);
                if (IsCallConnected())
                {
                    return;
                }
                iCounter++;
                if (iCounter > 4)
                {
                    throw new UnityConnectionRestException(res, "Failed to connect to phone" + res);
                }
            }

            throw new UnityConnectionRestException(res, "Failed to connect to phone" + res);
        }
Пример #46
0
 private string NoApplicableTargetMessage(CallType callType, Type[] types)
 {
     return(TypeErrorForOverloads("no overloads of {0} could match {1}", _targets, callType, types));
 }
Пример #47
0
        // (clr-new type arg1 ... )
        public override Expression Generate(object args, CodeBlock cb)
        {
            Type   t;
            string type;
            bool   inferred;

            object rtype = Builtins.First(args);

            ExtractTypeInfo(rtype, out t, out type, out inferred);

            if (t == null)
            {
                ClrSyntaxError("clr-new", "type not found", type);
            }

            Expression[] arguments = GetAstListNoCast(Builtins.Cdr(args) as Cons, cb);

            List <MethodBase> candidates = new List <MethodBase>();

            foreach (ConstructorInfo c in t.GetConstructors())
            {
                bool add = true;

                foreach (var pi in c.GetParameters())
                {
                    if (pi.ParameterType.IsPointer)
                    {
                        add = false;
                        break;
                    }
                }

                if (add)
                {
                    candidates.Add(c);
                }
            }

            if (t.IsValueType && arguments.Length == 0)
            {
                // create default valuetype here
                return(Ast.DefaultValueType(t));
            }

            Type[] types = new Type[arguments.Length];

            for (int i = 0; i < types.Length; i++)
            {
                types[i] = arguments[i].Type;
            }

            CallType ct = CallType.None;

            MethodBinder mb = MethodBinder.MakeBinder(Binder, "ctr", candidates, BinderType.Normal);

            MethodCandidate mc = mb.MakeBindingTarget(ct, types);

            if (mc == null)
            {
                types = new Type[arguments.Length];

                for (int i = 0; i < types.Length; i++)
                {
                    types[i] = typeof(object);
                }

                if (ct == CallType.ImplicitInstance)
                {
                    types = ArrayUtils.Insert(t, types);
                }

                mc = mb.MakeBindingTarget(ct, types);
            }

            ConstructorInfo ci = null;

            if (mc == null && candidates.Count > 0)
            {
                foreach (ConstructorInfo c in candidates)
                {
                    if (c.GetParameters().Length == arguments.Length)
                    {
                        ci = c;
                        break; // tough luck for now
                    }
                }
            }
            else
            {
                ci = mc.Target.Method as ConstructorInfo;
            }

            if (ci != null)
            {
                ParameterInfo[] pars = ci.GetParameters();
                for (int i = 0; i < arguments.Length; i++)
                {
                    Type tt = pars[i].ParameterType;
                    arguments[i] = ConvertToHelper(tt, arguments[i]);
                }

                Expression r = Ast.New(ci, arguments);
                return(r);
            }

            ClrSyntaxError("clr-new", "constructor could not be resolved on type: " + type, args);

            return(null);
        }
Пример #48
0
 private string MultipleTargetsMessage(List <MethodCandidate> applicableTargets, CallType callType, Type[] types)
 {
     return(TypeErrorForOverloads("multiple overloads of {0} could match {1}", applicableTargets, callType, types));
 }
Пример #49
0
        /// <summary>
        ///   Permet un appel générique de méthodes ou de propriétés d'un objet
        ///   sans que la structure de celui-ci ne soit connue.
        /// </summary>
        /// <param name="target"> Objet dont on veut lire ou éditer une méthode ou une propriété. </param>
        /// <param name="methodName"> Nom de la propriété ou de la méthode. On peut utiliser le séparateur '.' afin d'atteindre la propriété d'un sous objet. </param>
        /// <param name="callType"> Spécifie comment invoquer la méthode (lecture ou ecriture). </param>
        /// <param name="args"> Liste des arguments à passer dans la méthode. </param>
        /// <returns> Résultat de la propriété ou de l'invocation de la méthode. </returns>
        public static object CallByName(object target, string methodName, CallType callType, params object[] args)
        {
            string[] sousObjets = methodName.Split('.');

            try
            {
                if (sousObjets.Length <= 1)
                {
                    switch (callType)
                    {
                    case CallType.Get:
                    {
                        try
                        {
                            PropertyInfo p = target.GetType().GetProperty(methodName);
                            return(p.GetValue(target, args));
                        }
                        catch
                        {
                            FieldInfo f = target.GetType().GetField(methodName);
                            return(f.GetValue(target));
                        }
                    }

                    case CallType.Set:
                    {
                        try
                        {
                            PropertyInfo p = target.GetType().GetProperty(methodName);
                            p.SetValue(target, args[0], null);
                        }
                        catch
                        {
                            FieldInfo f = target.GetType().GetField(methodName);
                            f.SetValue(target, args[0]);
                        }
                        return(null);
                    }

                    case CallType.Method:
                    {
                        MethodInfo m = target.GetType().GetMethod(methodName);
                        return(m.Invoke(target, args));
                    }
                    }
                }
                else
                {
                    for (int i = 0; i < sousObjets.Length - 1; i++)
                    {
                        //Appeler la méthode jusqu'à ce que l'on atteingne la dernière propriété
                        target = CallByName(target, sousObjets[i], CallType.Get);
                    }
                    return(CallByName(target, sousObjets[sousObjets.Length - 1], callType, args));
                }
                return(null);
            }
            catch (MissingMemberException ex)
            {
                //La méthode CallByName a lancé une exception MissingMember dans sa récursive.
                throw new MissingMemberException(string.Format(CoreRessources.EX0027, methodName), ex);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException != null) //remet l'erreur dans l'erreur initiale
                {
                    throw ex.InnerException;
                }
            }
            return(null);
        }
Пример #50
0
        private string TypeErrorForOverloads(string message, List <MethodCandidate> targets, CallType callType, Type[] types)
        {
            StringBuilder buf = new StringBuilder();

            buf.AppendFormat(message, _binder._name, GetArgTypeNames(types, callType));
            buf.AppendLine();
            foreach (MethodCandidate target in targets)
            {
                buf.Append("  ");
                buf.AppendLine(target.ToSignatureString(_binder._name, callType));
            }
            return(buf.ToString());
        }
Пример #51
0
        public Request(string url, Dictionary <string, string> body, RequestType requestType, CallType callType = CallType.General, bool isAbsolute = false)
        {
            if (!isAbsolute)
            {
                this.url = GameApiScript.formAbsoluteURL(url);
            }
            else
            {
                this.url = url;
            }
            this.body = body;

            this.requestType = requestType;
            this.callType    = callType;

            isJsonType = false;
            refreshHeaders();
        }
Пример #52
0
        public async Task Create(CallType callType)
        {
            await _session.SaveAsync(callType);

            await _session.FlushAsync();
        }
Пример #53
0
        public async Task <string> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "callbackend")] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            CallType callType = (CallType)Enum.Parse(typeof(CallType), req.Query["callType"], true);

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            _tenantId     = config["AzureAd:TenantId"];
            _clientId     = config["AzureAd:ClientId"];
            _clientSecret = config["AzureAd:ClientSecret"];
            _backendUrl   = config["BackendUrl"];
            _scopes       = new string[] { $"api://{config["AzureAd:BackendClientId"]}/.default" };

            var app = ConfidentialClientApplicationBuilder.Create(_clientId)
                      .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
                      .WithClientSecret(_clientSecret)
                      .Build();

            AuthenticationResult result = null;

            try
            {
                result = await app.AcquireTokenForClient(_scopes)
                         .ExecuteAsync();
            }
            catch (MsalServiceException ex)
            {
                throw ex;
            }

            _httpClient.SetAuthenticationHeader("Bearer", result.AccessToken);

            string uri = string.Empty;

            switch (callType)
            {
            case CallType.Echo:
                uri = $"{_backendUrl}/api/echo/daemon echo call";
                break;

            case CallType.Claim:
                uri = $"{_backendUrl}/api/claim";
                break;
            }

            var response = await _httpClient.GetAsync(uri);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"CallBackend function failed with status code {response.StatusCode}. Reason phrase: {response.ReasonPhrase}");
            }

            string responseContent = await response.Content.ReadAsStringAsync();

            return(responseContent);
        }
Пример #54
0
        public async Task Update(CallType callType)
        {
            await _session.UpdateAsync(callType);

            await _session.FlushAsync();
        }
Пример #55
0
        public async Task Delete(CallType callType)
        {
            await _session.DeleteAsync(callType);

            await _session.FlushAsync();
        }
Пример #56
0
        /// <summary>
        /// Generates stub to receive the CLR call and then call the dynamic language code.
        /// </summary>
        public static void  EmitClrCallStub(CodeGen cg, Slot callTarget, int firstArg, CallType functionAttributes)
        {
            List <ReturnFixer> fixers = new List <ReturnFixer>(0);
            IList <Slot>       args   = cg.ArgumentSlots;
            int nargs = args.Count - firstArg;

            CallAction action;

            if ((functionAttributes & CallType.ArgumentList) != 0)
            {
                ArgumentInfo[] infos = CompilerHelpers.MakeRepeatedArray(ArgumentInfo.Simple, nargs);
                infos[nargs - 1] = new ArgumentInfo(ArgumentKind.List);

                action = CallAction.Make(new CallSignature(infos));
            }
            else
            {
                action = CallAction.Make(nargs);
            }

            bool fast;
            Slot site = cg.CreateDynamicSite(action,
                                             CompilerHelpers.MakeRepeatedArray(typeof(object), nargs + 2),
                                             out fast);

            site.EmitGet(cg);
            if (!fast)
            {
                cg.EmitCodeContext();
            }

            if (DynamicSiteHelpers.IsBigTarget(site.Type))
            {
                cg.EmitTuple(site.Type.GetGenericArguments()[0], args.Count + 1, delegate(int index) {
                    if (index == 0)
                    {
                        callTarget.EmitGet(cg);
                    }
                    else
                    {
                        ReturnFixer rf = ReturnFixer.EmitArgument(cg, args[index - 1]);
                        if (rf != null)
                        {
                            fixers.Add(rf);
                        }
                    }
                });
            }
            else
            {
                callTarget.EmitGet(cg);

                for (int i = firstArg; i < args.Count; i++)
                {
                    ReturnFixer rf = ReturnFixer.EmitArgument(cg, args[i]);
                    if (rf != null)
                    {
                        fixers.Add(rf);
                    }
                }
            }

            cg.EmitCall(site.Type, "Invoke");

            foreach (ReturnFixer rf in fixers)
            {
                rf.FixReturn(cg);
            }
            cg.EmitReturnFromObject();
        }
Пример #57
0
 public Function(Module mod, Addr32 addr, CallType call)
 {
     module = mod;
     address = addr;
     callType = call;
 }
Пример #58
0
 public Call(Player player, CallType type)
 {
     Player = player;
     Type   = type;
 }
Пример #59
0
 public MethodCandidate MakeBindingTarget(CallType callType, Type[] types)
 {
     Type[] dummy;
     return(MakeBindingTarget(callType, types, out dummy));
 }
Пример #60
0
        /// <summary>
        /// Update call details
        /// </summary>
        /// <param name="campaign"></param>
        /// <param name="callDetail"></param>
        /// <param name="CallType"></param>
        /// <returns></returns>
        public static bool UpdateCallDetails(Campaign objCampaign, CampaignDetails callDetail, CallType CallType, long queryId)
        {
            DialerEngine.Log.Write("|CA|{0}|{1}|Update call details invoked.", objCampaign.CampaignID, objCampaign.ShortDescription);
            CampaignService objCampService = null;
            XmlDocument     xDocCallDetail = null;
            XmlDocument     xDocCampaign   = null;

            try
            {
                if (callDetail != null)
                {
                    objCampService = new CampaignService();
                    xDocCampaign   = new XmlDocument();
                    xDocCampaign.LoadXml(Serialize.SerializeObject(objCampaign, "Campaign"));
                    xDocCallDetail = new XmlDocument();
                    xDocCallDetail.LoadXml(Serialize.SerializeObject(callDetail, "CampaignDetails"));
                    objCampService.UpdateCallDetail(xDocCampaign, xDocCallDetail, (int)CallType, queryId);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                DialerEngine.Log.WriteException(ex, "Error in UpdateCallDetails");
            }
            finally
            {
                objCampService = null;
                xDocCampaign   = null;
            }
            return(false);
        }