Beispiel #1
0
 public List<ContactInfo> AddContacts(List<ContactInfo> lstContacts, bool isWeb)
 {
     try
     {
         ContactManager mgr = new ContactManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.AddContacts(tokenInfo.Idf, lstContacts);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #2
0
 public List<ContactHeaderInfo> GetFollowerFollowingList(bool isFollowerList, bool isWeb)
 {
     try
     {
         ContactManager mgr = new ContactManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.GetCategorizedContactList(tokenInfo.Idf, false, isFollowerList, !isFollowerList, false);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
    void Awake()
    {

        helperMethods = new HelperMethods();

        //Float
        RiverStartPointsPerPolygon = 4;
        HexagonRadius = 10000; //Using value 2582258 is equivalent to earth in size
        PentagonRadius = HexagonRadius / ((float)Math.Sin(36 * Mathf.Deg2Rad) * 2);
        PentagonApothem = PentagonRadius * (Mathf.Cos(36 * Mathf.Deg2Rad));
        HexagonApothem = HexagonRadius * (Mathf.Cos(30 * Mathf.Deg2Rad));
        PentagonEdgeLength = (2 * PentagonRadius * (Mathf.Sin(180 / 5)));

        //int
        plateRatioSeed = 1;
       
        //Array
        PolygonVertices = new Vector3[32, 6];
        continentVertices = new Vector3[32, 7];
        PolygonYIntercepts = new float[32, 6];

        //list
        PentagonSlopes = new List<float>();
        HexagonSlopes = new List<float>();
        FPentagonSlopes = new List<float>();

        tectonicNoise = new PerlinNoise(plateRatioSeed);
        PolygonPlatePoints = new int[32, 2];
        RiverMouths = new int[32, 4];
        RiverStartPoints = new Vector3[32, RiverStartPointsPerPolygon];
        RiverStartDirection = new int[32, RiverStartPointsPerPolygon];
        RiverMidpoints = new Vector3[32, 4];
        ActiveRiverMidpoints = new bool[32, 3];
        PolygonNeighbours = new int[32, 4];
        RiverStartToMid = new int[32, 4];
        RiverMidToMouth = new int[32, 4];

        generateStaticValues();
        generatePentagons();
        generateHexagons();
        generateFPentagons();
        generateContinentVertices();
        generateTectonicPoints();
        generateRiverStartpoints();
        generateRiverMouths();
        generateRiverMidpoints();
        linkRiverStartToMid();

    }
Beispiel #4
0
 public CommentInfo AddComment(long postId, CommentInfo info, bool isWeb)
 {
     try
     {
         CommentManager mgr = new CommentManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         info.PostId = postId;
         info.UserIdf = tokenInfo.Idf;
         return mgr.AddComment(info, tokenInfo.TerritoryId);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #5
0
        public bool BlockUnBlockUser(string contactToken, bool isWeb, bool allowed)
        {
            try
            {
                UserManager mgr = new UserManager();
                TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
                if (!String.IsNullOrWhiteSpace(contactToken))
                {
                    if (allowed)
                        return mgr.UnBlockUser(tokenInfo.Idf, JsonWebToken.DecodeToken<TokenInfo>(contactToken, CodeHelper.SecretAccessKey, true, false).Idf);
                    return mgr.BlockUser(tokenInfo.Idf, JsonWebToken.DecodeToken<TokenInfo>(contactToken, CodeHelper.SecretAccessKey, true, false).Idf);
                }

                throw new Exception(CodeHelper.UnableToUpdateProfilePicture);
            }
            catch (Exception ex)
            {
                throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
            }
        }
Beispiel #6
0
        /// <summary>
        /// This method will access the license keys that belong to the user by asking them to
        /// login into their account and authorize this application to get a token that will
        /// return them. In rare cases, we may get a successful authorization but not successful
        /// retrieval of license keys. In this case, the value tuple that is returned by this
        /// method will contain a token (Item3/licenseKeyToken). Next time you try to repeat
        /// the attempt, pass in the returned token into "existingToken" parameter.
        /// </summary>
        /// <param name="machineCode">The machine code you want to authorize.</param>
        /// <param name="token">The token to access the "GetToken" method.</param>
        /// <param name="appName">A user friendly name of your application.</param>
        /// <param name="tokenExpires">Sets the number of days the token should be valid.</param>
        /// <param name="RSAPublicKey">The RSA public key can be found here:
        /// https://app.cryptolens.io/User/Security </param>
        /// <param name="existingToken">If you have already called this method once
        /// and received a token as a result (despite an error), you can enter it here
        /// to avoid duplicate authorization by the user.</param>
        public static GetLicenseKeysResult GetLicenseKeys(string machineCode, string token, string appName, int tokenExpires, string RSAPublicKey, string existingToken = null)
        {
            string tokenNew = existingToken;

            if (string.IsNullOrEmpty(existingToken))
            {
                var auth = AuthMethods.CreateAuthRequest(new Scope {
                    GetLicenseKeys = true
                }, appName, machineCode, AuthMethods.GetTokenId(token), tokenExpires);

                for (int i = 0; i < 100; i++)
                {
                    try
                    {
                        tokenNew = AuthMethods.GetToken(auth, token);
                    }
                    catch (Exception ex) { }

                    if (tokenNew != null)
                    {
                        break;
                    }

                    Thread.Sleep(3000);
                }

                if (tokenNew == null)
                {
                    return(new GetLicenseKeysResult {
                        Error = "Timeout reached. The user took too long time to authorize this request."
                    });
                }
            }

            GetLicenseKeysResultLinqSign result = null;

            try
            {
                result = HelperMethods.SendRequestToWebAPI3 <GetLicenseKeysResultLinqSign>(new GetLicenseKeysModel {
                    Sign = true, MachineCode = machineCode
                }, "/User/GetLicenseKeys", tokenNew);
            }
            catch (Exception ex)
            {
                return(new GetLicenseKeysResult {
                    LicenseKeyToken = tokenNew, Error = "Could not contact SKM: " + ex.InnerException
                });
            }


            if (result == null || result.Result == ResultType.Error)
            {
                return(new GetLicenseKeysResult {
                    LicenseKeyToken = tokenNew, Error = "An error occurred in the method: " + result?.Message
                });
            }


            var licenseKeys       = Convert.FromBase64String(result.Results);
            var activatedMachines = Convert.FromBase64String(result.ActivatedMachineCodes);

            var date = BitConverter.GetBytes(result.SignDate);

            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(date);
            }

            var toSign = licenseKeys.Concat(activatedMachines.Concat(date)).ToArray();

            // only if sign enabled.
#if NET40 || NET46 || NET35 || NET45
            using (var rsaVal = new RSACryptoServiceProvider())
            {
                rsaVal.FromXmlString(RSAPublicKey);

                if (!rsaVal.VerifyData(toSign, "SHA256", Convert.FromBase64String(result.Signature)))
                {
                    // verification failed.
                    return(new GetLicenseKeysResult {
                        LicenseKeyToken = tokenNew, Error = "Verification of the signature failed."
                    });
                }
            }
#else
            using (var rsaVal = RSA.Create())
            {
                rsaVal.ImportParameters(SecurityMethods.FromXMLString(RSAPublicKey));

                if (!rsaVal.VerifyData(toSign, Convert.FromBase64String(result.Signature),
                                       HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1))
                {
                    // verification failed.
                    return(new GetLicenseKeysResult {
                        LicenseKeyToken = tokenNew, Error = "Verification of the signature failed."
                    });
                }
            }
#endif

            var machineCodes = JsonConvert.DeserializeObject <List <String> >(System.Text.UTF8Encoding.UTF8.GetString(activatedMachines));
            if (machineCodes?.Count != 0 && !machineCodes.Contains(machineCode))
            {
                return(new GetLicenseKeysResult {
                    LicenseKeyToken = tokenNew, Error = "This machine code has not been authorized."
                });
            }


            return(new GetLicenseKeysResult
            {
                Licenses = JsonConvert.DeserializeObject <List <KeyInfoResult> >(System.Text.UTF8Encoding.UTF8.GetString((licenseKeys))).Select(x => x.LicenseKey).ToList(),
                LicenseKeyToken = tokenNew
            });
        }
 protected override async void OnNavigatedTo(NavigationEventArgs e)
 {
     HelperMethods.EnableBackButton();
     await Vm.OnNavigatedTo((SpotifyAlbum)e.Parameter);
 }
Beispiel #8
0
 public bool FollowUnFollowUser(string contactToken, bool isWeb, bool follow)
 {
     try
     {
         UserManager mgr = new UserManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         if (!String.IsNullOrWhiteSpace(contactToken))
         {
             if (follow)
             {
                 TokenInfo contact = JsonWebToken.DecodeToken<TokenInfo>(contactToken, CodeHelper.SecretAccessKey, true, false);
                 NotificationInfo info = mgr.FollowUser(tokenInfo.Idf, contact.Idf, tokenInfo.TerritoryId);
                 var obj = GlobalHost.ConnectionManager.GetHubContext<HeyVoteHub>();
                 obj.Clients.Client(contact.Idf.ToString()).notifyUsers(new
                 {
                     Id = info.Id,
                     Title = info.Title,
                     UserIdf = info.UserIdf,
                     ImageIdf = info.ImageIdf,
                     FolderPath = info.FolderPath,
                     CreatedOn = info.CreatedOn,
                     DisplayName = info.DisplayName,
                 });
                 return true;
             }
             return mgr.UnFollowUser(tokenInfo.Idf, JsonWebToken.DecodeToken<TokenInfo>(contactToken, CodeHelper.SecretAccessKey, true, false).Idf);
         }
         throw new Exception(CodeHelper.UnableToUpdateProfilePicture);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #9
0
 public List<PostInfo> GetPostListByTerritoryId(int pageId, int pageSize, int territoryId, bool isWeb)
 {
     try
     {
         PostManager mgr = new PostManager();
         HelperMethods helperMgr = new HelperMethods();
         TokenInfo tokenInfo = helperMgr.GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.GetPostListByTerritoryId(tokenInfo.Idf, tokenInfo.FolderPath, pageId, helperMgr.SetPageSize(pageSize, isWeb), territoryId == 0 ? tokenInfo.TerritoryId : territoryId);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #10
0
        public override void Run(List <Point> points, List <Line> lines, List <Polygon> polygons, ref List <Point> outPoints, ref List <Line> outLines, ref List <Polygon> outPolygons)
        {
            //1- get minimum the point Y
            //2- get angles between Horizontal Line and all points put it in List<pair> with their index
            //3- sort points put points in list then sort
            //4- create stack and push points p0,p1
            //5- loop i:2->n top,preTop
            // if pretop.top turn left with pi then push pi in stack then i++
            // else pop from stack
            // complexity O(nlogn)
            List <Point> myPoints = new List <Point>();

            for (int i = 0; i < points.Count; i++)
            {
                if (!myPoints.Contains(points[i]))
                {
                    myPoints.Add(points[i]);
                }
            }
            if (myPoints.Count < 3)
            {
                for (int i = 0; i < myPoints.Count; i++)
                {
                    outPoints.Add(myPoints[i]);
                }
                return;
            }
            Point  myMinimumPoint = new Point(0, 0);
            var    yminimumIndex  = -1;
            double minimum        = 1e9;

            for (int i = 0; i < myPoints.Count; i++)
            {
                var y = myPoints[i].Y;
                if ((y < minimum) || (y == minimum && myPoints[i].X < myMinimumPoint.X))
                {
                    minimum        = y;
                    yminimumIndex  = i;
                    myMinimumPoint = myPoints[i];
                }
            }
            myPoints[yminimumIndex] = myPoints[0];
            myPoints[0]             = myMinimumPoint;
            OrderedSet <PointWithAngle> pointsSorted = new OrderedSet <PointWithAngle>(new Comparison <PointWithAngle>(HelperMethods.compareTwoPointsByAngle));

            pointsSorted.Add(new PointWithAngle(myPoints[0], 0));
            for (int i = 1; i < myPoints.Count; i++)
            {
                Point  temp    = new Point(myPoints[0].X + 10, myPoints[0].Y);
                double myAngle = HelperMethods.CalculateAngle(temp, myPoints[0], myPoints[i]);
                pointsSorted.Add(new PointWithAngle(myPoints[i], myAngle));
            }
            Stack <Point> myStack = new Stack <Point>();

            for (int i = 0; i < 3; i++)
            {
                myStack.Push(pointsSorted[i].myPoint);
            }
            for (int i = 3; i < pointsSorted.Count; i++)
            {
                Point top       = myStack.Peek();
                Point nextToTop = HelperMethods.FindnextPointInStack(myStack);
                while (HelperMethods.CheckTurn(new Line(nextToTop, top), pointsSorted[i].myPoint) != Enums.TurnType.Left)
                {
                    myStack.Pop();
                    top       = myStack.Peek();
                    nextToTop = HelperMethods.FindnextPointInStack(myStack);
                }
                myStack.Push(pointsSorted[i].myPoint);
            }
            while (myStack.Count != 0)
            {
                outPoints.Add(myStack.Pop());
            }
        }
Beispiel #11
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and 
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Warning that this component is OBSOLETE
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This component is OBSOLETE and will be removed " +
                "in the future. Remove this component from your canvas and replace it by picking the new component " +
                "from the ribbon.");

            // Input variables
            string name = "default_tool";
            List<Mesh> meshes = new List<Mesh>();
            Plane attachmentPlane = Plane.Unset;
            Plane toolPlane = Plane.Unset;

            // Catch the input data
            if (!DA.GetData(0, ref name)) { return; }
            if (!DA.GetDataList(1, meshes)) { meshes = new List<Mesh>() { new Mesh() }; }
            if (!DA.GetData(2, ref attachmentPlane)) { return; }
            if (!DA.GetData(3, ref toolPlane)) { return; };

            // Create the Robot Tool
            _robotTool = new RobotTool(name, meshes, attachmentPlane, toolPlane);

            // Outputs
            DA.SetData(0, _robotTool);
            DA.SetData(1, _robotTool.ToRAPIDDeclaration());

            #region Object manager
            // Gets ObjectManager of this document
            _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument());

            // Clears tool name
            _objectManager.ToolNames.Remove(_toolName);
            _toolName = String.Empty;

            // Removes lastName from toolNameList
            if (_objectManager.ToolNames.Contains(_lastName))
            {
                _objectManager.ToolNames.Remove(_lastName);
            }

            // Adds Component to ToolsByGuid Dictionary
            if (!_objectManager.OldRobotToolFromPlanesGuid.ContainsKey(this.InstanceGuid))
            {
                _objectManager.OldRobotToolFromPlanesGuid.Add(this.InstanceGuid, this);
            }

            // Checks if the tool name is already in use and counts duplicates
            #region Check name in object manager
            if (_objectManager.ToolNames.Contains(_robotTool.Name))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Tool Name already in use.");
                _nameUnique = false;
                _lastName = "";
            }
            else
            {
                // Adds Robot Tool Name to list
                _toolName = _robotTool.Name;
                _objectManager.ToolNames.Add(_robotTool.Name);

                // Run SolveInstance on other Tools with no unique Name to check if their name is now available
                _objectManager.UpdateRobotTools();

                _lastName = _robotTool.Name;
                _nameUnique = true;
            }

            // Checks if variable name exceeds max character limit for RAPID Code
            if (HelperMethods.VariableExeedsCharacterLimit32(name))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Robot Tool Name exceeds character limit of 32 characters.");
            }

            // Checks if variable name starts with a number
            if (HelperMethods.VariableStartsWithNumber(name))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Robot Tool Name starts with a number which is not allowed in RAPID Code.");
            }
            #endregion

            // Recognizes if Component is Deleted and removes it from Object Managers tool and name list
            GH_Document doc = this.OnPingDocument();
            if (doc != null)
            {
                doc.ObjectsDeleted += DocumentObjectsDeleted;
            }
            #endregion
        }
Beispiel #12
0
 public ProfileInfo ViewProfileExternal(string contactToken, bool isWeb)
 {
     try
     {
         UserManager mgr = new UserManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         if (!String.IsNullOrWhiteSpace(contactToken))
         {
             TokenInfo contactTokenInfo = JsonWebToken.DecodeToken<TokenInfo>(contactToken, CodeHelper.SecretAccessKey, true, false);
             return mgr.ViewProfileExternal(tokenInfo.Idf, contactTokenInfo.Idf, Convert.ToInt32(contactTokenInfo.TerritoryId));
         }
         throw new Exception(CodeHelper.UnableToUpdateProfilePicture);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #13
0
 public bool UpdateStatus(string status, bool isWeb)
 {
     try
     {
         UserManager mgr = new UserManager();
         Guid userIdf = new HelperMethods().GetUserIdf(isWeb, HttpContext.Current);
         return mgr.UpdateStatus(userIdf, status);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #14
0
 public List<SearchInfo> SearchUsers(string searchString,int pageId, int pageSize, bool isWeb)
 {
     try
     {
         UserManager mgr = new UserManager();
         HelperMethods helperMgr = new HelperMethods();
         TokenInfo tokenInfo = helperMgr.GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.SearchUsers(tokenInfo.Idf, searchString, pageId, helperMgr.SetPageSize(pageSize, isWeb));
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #15
0
 public string RemoveProfilePicture(bool isWeb)
 {
     try
     {
         UserManager mgr = new UserManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.RemoveProfilePicture(tokenInfo.Idf, tokenInfo.FolderPath);
         throw new Exception(CodeHelper.UnableToUpdateProfilePicture);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #16
0
 public string RegisterSignalR(string signalRIdf)
 {
     try
     {
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(true, HttpContext.Current);
         HeyVoteHub.MyUsers.TryAdd(signalRIdf, tokenInfo.Idf.ToString());
         return true.ToString();
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #17
0
 public List<CommentInfo> GetOwnComments(long postId, int pageId, int pageSize, bool isWeb)
 {
     try
     {
         CommentManager mgr = new CommentManager();
         HelperMethods helperMgr = new HelperMethods();
         Guid userIdf = helperMgr.GetUserIdf(isWeb, HttpContext.Current);
         return mgr.GetOwnComments(userIdf, postId, pageId, helperMgr.SetPageSize(pageSize, isWeb));
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #18
0
        public static void Initialize(APIContext context)
        {
            context.Database.EnsureCreated();

            // Look for any students.
            if (!context.Users.Any())
            {
                // add base users if data base not populated
                User[] users = new User[]
                {
                    new User {
                        First_Name = "John", Last_Name = "Doe", Email = "*****@*****.**", Password = HelperMethods.ConcatenatedSaltAndSaltedHash("useless"), NumAccs = 2, Role = UserRoles.User
                    },
                    new User {
                        First_Name = "Edwin", Last_Name = "May", Email = "*****@*****.**", Password = HelperMethods.ConcatenatedSaltAndSaltedHash("useless"), NumAccs = 2, Role = UserRoles.User
                    },
                    new User {
                        First_Name = "Lucy", Last_Name = "Vale", Email = "*****@*****.**", Password = HelperMethods.ConcatenatedSaltAndSaltedHash("useless"), NumAccs = 2, Role = UserRoles.User
                    },
                    new User {
                        First_Name = "Pam", Last_Name = "Willis", Email = "*****@*****.**", Password = HelperMethods.ConcatenatedSaltAndSaltedHash("useless"), NumAccs = 2, Role = UserRoles.User
                    },
                    new User {
                        First_Name = "Game", Last_Name = "Stonk", Email = "*****@*****.**", Password = HelperMethods.ConcatenatedSaltAndSaltedHash("useless"), NumAccs = 2, Role = UserRoles.User
                    }
                };

                foreach (User person in users)
                {
                    context.Users.Add(person); // add each user to the table
                }
                context.SaveChanges();         // execute changes

                // create a key and iv for these base users
                foreach (User person in context.Users)
                {
                    HelperMethods.CreateUserKeyandIV(person.ID);
                }
            }

            if (!context.Accounts.Any())
            {
                // add 2 base accounts to each user for testing
                Account[] accs = new Account[]
                {
                    new Account {
                        UserID = 1, Title = "gmail", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(1)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 1, Title = "yahoo", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(1)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 2, Title = "paypal", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(2)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 2, Title = "zoom", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(2)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 3, Title = "chase", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(3)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 3, Title = "netflix", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(3)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 4, Title = "hulu", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(4)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 4, Title = "amazon", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(4)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 5, Title = "spotify", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(5)), Description = "Add description here.."
                    },
                    new Account {
                        UserID = 5, Title = "bestbuy", Login = "******", Password = HelperMethods.EncryptStringToBytes_Aes("useless", HelperMethods.GetUserKeyAndIV(5)), Description = "Add description here.."
                    }
                };

                foreach (Account acc in accs)
                {
                    context.Accounts.Add(acc);
                }                      // add each account to the table
                context.SaveChanges(); // execute changes
            }

            if (!context.Folders.Any())
            {
                // add base folders
                Folder[] base_folds = new Folder[]
                {
                    new Folder {
                        UserID = 1, FolderName = "Folder", HasChild = true
                    },
                    new Folder {
                        UserID = 2, FolderName = "Folder", HasChild = true
                    },
                    new Folder {
                        UserID = 3, FolderName = "Folder", HasChild = true
                    },
                    new Folder {
                        UserID = 4, FolderName = "Folder", HasChild = true
                    },
                    new Folder {
                        UserID = 5, FolderName = "Folder", HasChild = true
                    }
                };

                Folder[] sub_folds = new Folder[]
                {
                    new Folder {
                        UserID = 1, FolderName = "Sub-Folder", HasChild = false, ParentID = 5
                    },
                    new Folder {
                        UserID = 2, FolderName = "Sub-Folder", HasChild = false, ParentID = 4
                    },
                    new Folder {
                        UserID = 3, FolderName = "Sub-Folder", HasChild = false, ParentID = 3
                    },
                    new Folder {
                        UserID = 4, FolderName = "Sub-Folder", HasChild = false, ParentID = 2
                    },
                    new Folder {
                        UserID = 5, FolderName = "Sub-Folder", HasChild = false, ParentID = 1
                    }
                };

                foreach (Folder fold in base_folds)
                {
                    context.Folders.Add(fold);
                }                                                                  // add each account to the table
                context.SaveChanges();
                foreach (Folder fold in sub_folds)
                {
                    context.Folders.Add(fold);
                }                      // add each account to the table
                context.SaveChanges(); // execute changes
            }
        }
    public static void Main()
    {
        var substr = HelperMethods.Subsequence("Hello!".ToCharArray(), 2, 3);

        Console.WriteLine(substr);

        var subarr = HelperMethods.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 2);

        Console.WriteLine(string.Join(" ", subarr));

        var allarr = HelperMethods.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 4);

        Console.WriteLine(string.Join(" ", allarr));

        var emptyarr = HelperMethods.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 0);

        Console.WriteLine(string.Join(" ", emptyarr));

        string endCharacters = HelperMethods.ExtractEnding("I love C#", 2);

        Console.WriteLine(endCharacters);
        endCharacters = HelperMethods.ExtractEnding("Nakov", 4);
        Console.WriteLine(endCharacters);
        endCharacters = HelperMethods.ExtractEnding("beer", 4);
        Console.WriteLine(endCharacters);
        endCharacters = HelperMethods.ExtractEnding("Hi", 100);
        Console.WriteLine(endCharacters);

        try
        {
            HelperMethods.CheckPrime(23);
            Console.WriteLine("23 is a prime number.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("ErrorMessage: {0}", ex.Message);
        }

        try
        {
            HelperMethods.CheckPrime(33);
            Console.WriteLine("33 is a prime number.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("ErrorMessage: {0}", ex.Message);
        }

        List <Exam> peterExams = new List <Exam>()
        {
            new SimpleMathExam(2),
            new CSharpExam(55),
            new CSharpExam(100),
            new SimpleMathExam(1),
            new CSharpExam(0),
        };
        Student peter = new Student("Peter", "Petrov", peterExams);
        double  peterAverageResult = peter.CalcAverageExamResultInPercents();

        Console.WriteLine("Average results = {0:p0}", peterAverageResult);
    }
Beispiel #20
0
 public string ChangeProfilePicture(string data, bool isWeb)
 {
     try
     {
         UserManager mgr = new UserManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         if (!String.IsNullOrWhiteSpace(data))
             return mgr.ChangeProfilePicture(tokenInfo.Idf, tokenInfo.FolderPath, JsonWebToken.Base64UrlDecode(data));
         throw new Exception(CodeHelper.UnableToUpdateProfilePicture);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
 public static void Build(DocumentBuilder builder)
 {
     builder.Writeln();
     builder.Writeln(HelperMethods.CreateCompanyContactInfoText(true));
 }
    void Awake()
    {

        //Array       
        TerrainClassificationBlank = new int[3, 5];

        //Int        
        terrainSize = 500;
        Spread = 2;
        LowDetailSpread = (Spread * 2 + 1) + Spread;
        
        totalTiles = (Spread * 2 + 1) * (Spread * 2 + 1);
        totalDistantTiles = ((LowDetailSpread * 2 + 1) * (LowDetailSpread * 2 + 1));

        TERRAIN_BUFFER_COUNT = totalTiles * 2;
        DISTANT_TERRAIN_BUFFER_COUNT = totalDistantTiles * 2;

        m_heightMapSizeHighRes = 65; //Higher number will create more detailed height maps
        m_heightMapSizeLowRes = 7; //Low res heightmap used for bulk distance terrain generation
        m_alphaMapSize = 33; //This is the control map that controls how the splat textures will be blended
        m_terrainHeight = 4096; //Allows mountains up to Everest height to be added 9216

        m_groundSeed = 0; //Noise map seed
        m_mountainSeed = 1; //Noise map seed
        m_islandSeed = 2; //Noise map seed
        m_riverSeed = 3; //Noise map seed

        //Float
        m_pixelMapError = 10.0f; //A lower pixel error will draw terrain at a higher Level of detail but will be slower
        m_baseMapDist = 500.0f; //The distance at which the low res base map will be drawn. Decrease to increase performance
        m_groundFrq = 800.0f; //Noise settings. A higher frq will create larger scale details
        m_mountainFrq = 200f; //Noise settings. A higher frq will create larger scale details
        m_islandFrq = 1200f; //Noise settings. A higher frq will create larger scale details
        m_splatTileSize0 = 10.0f;
        m_splatTileSize1 = 2.0f;

        //Initialise all array, dictionaries, noise
        terrainUsage = new Dictionary<string, int>();
        distantTerrainUsage = new Dictionary<string, int>();

        terrainUsageData = new Dictionary<string, TerrainData>();
        distantTerrainMesh = new Dictionary<string, Mesh>();
        waterMesh = new Dictionary<string, Mesh>();

        HeightMaps = new Dictionary<string, float[,]>();

        HeightMapsDistant = new Dictionary<string, float[,]>();

        TerrainTypeRegistration = new Dictionary<string, int[]>();
        RiverMeshHeights = new Dictionary<string, float[]>();
        RiverUsage = new Dictionary<string, int>();

        tileQueue = new List<Vector2>();
        tileQueueNonIndex = new HashSet<string>();

        tileQueueDistant = new List<Vector2>();
        tileQueueDistantNonIndex = new HashSet<string>();

        tileQueueTouched = new List<Vector2>();
        tileQueueTouchedDistant = new List<Vector2>();

        m_terrain = new Terrain[TERRAIN_BUFFER_COUNT];

        tileClassifications = new int[TERRAIN_BUFFER_COUNT][,]; //Array that holds int values that defines the characteristics of the Terrain tile
        for (int i = 0; i < TERRAIN_BUFFER_COUNT; i++)
        {

            tileClassifications[i] = TerrainClassificationBlank; //int[3,5]
            //0 = Terrain
            //0,0 = Mountains
            //0,1 = Hills
            //0,2 = Valley

            //1 = Water
            //1,0 = StartMid
            //1,1 = MidMouth
            //1,2 = MouthOcean
            //1,3 = Tributary

            //2 = Climate etc later
        }

        usedTiles = new BitArray(TERRAIN_BUFFER_COUNT, false);
        touchedTiles = new BitArray(TERRAIN_BUFFER_COUNT, false);
        WaterPlanes = new GameObject[TERRAIN_BUFFER_COUNT];
        DistantMesh = new GameObject[DISTANT_TERRAIN_BUFFER_COUNT];
        usedDistantTerrain = new BitArray(DISTANT_TERRAIN_BUFFER_COUNT, false);
        touchedDistantTerrain = new BitArray(DISTANT_TERRAIN_BUFFER_COUNT, false);

        m_groundNoise = new PerlinNoise(m_groundSeed);
        m_mountainNoise = new PerlinNoise(m_mountainSeed);
        m_mountainNoise2 = new PerlinNoise(12);
        m_islandNoise = new PerlinNoise(m_islandSeed);

        //m_offset = new Vector2(-m_terrainSize.x * 50 * 0.5f, -m_terrainSize.y * 50 * 0.5f);
        tilesWithMeshChanged = new HashSet<string>();

        helperMethods = new HelperMethods();

    }
Beispiel #23
0
        public IEnumerator AnimateFade(bool toBackground, HelperMethods.TypeOfAnimation animType, bool clear, float duration = 0.25f)
        {
            gameObject.SetActive(true);
            ScrollView.panel.depth = toBackground ? 2 : 999;

            // fade
            HelperMethods.FadeObject(ScrollView.gameObject, animType, duration);

            // scale
            Vector3 scaleFrom = Vector3.one;
            Vector3 scaleTo = toBackground ? HelperMethods.CloseToZeroVec : HelperMethods.BigScreenSizeVec;
            if (animType == HelperMethods.TypeOfAnimation.AnimationIn)
            {
                var tmp = scaleFrom;
                scaleFrom = scaleTo;
                scaleTo = tmp;
            }
            yield return StartCoroutine(HelperMethods.InterpolateScale(gameObject, scaleFrom, scaleTo, duration));

            // finishing up
            if (clear)
                Clear();

            if (animType == HelperMethods.TypeOfAnimation.AnimationOut)
                Recenter();

            ScrollView.panel.depth = 2;
        }
Beispiel #24
0
        public SettingRegRespObj DeleteProfessionalBody(DeleteProfessionalBodyObj regObj)
        {
            var response = new SettingRegRespObj
            {
                Status = new APIResponseStatus
                {
                    IsSuccessful = false,
                    Message      = new APIResponseMessage()
                }
            };

            try
            {
                if (regObj.Equals(null))
                {
                    response.Status.Message.FriendlyMessage  = "Error Occurred! Unable to proceed with your request";
                    response.Status.Message.TechnicalMessage = "Registration Object is empty / invalid";
                    return(response);
                }

                if (!EntityValidatorHelper.Validate(regObj, out var valResults))
                {
                    var errorDetail = new StringBuilder();
                    if (!valResults.IsNullOrEmpty())
                    {
                        errorDetail.AppendLine("Following error occurred:");
                        valResults.ForEachx(m => errorDetail.AppendLine(m.ErrorMessage));
                    }
                    else
                    {
                        errorDetail.AppendLine(
                            "Validation error occurred! Please check all supplied parameters and try again");
                    }
                    response.Status.Message.FriendlyMessage  = errorDetail.ToString();
                    response.Status.Message.TechnicalMessage = errorDetail.ToString();
                    response.Status.IsSuccessful             = false;
                    return(response);
                }

                if (!HelperMethods.IsUserValid(regObj.AdminUserId, regObj.SysPathCode,
                                               HelperMethods.getSeniorAccountant(), ref response.Status.Message))
                {
                    return(response);
                }
                var thisProfessionalBody = getProfessionalBodyInfo(regObj.ProfessionalBodyId);

                if (thisProfessionalBody == null)
                {
                    response.Status.Message.FriendlyMessage =
                        "No Professional Body Information found for the specified ProfessionalBody Id";
                    response.Status.Message.TechnicalMessage = "No Professional Body Information found!";
                    return(response);
                }
                thisProfessionalBody.Name = thisProfessionalBody.Name + "_Deleted_" +
                                            DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss");
                thisProfessionalBody.Status = ItemStatus.Deleted;
                var added = _repository.Update(thisProfessionalBody);
                _uoWork.SaveChanges();

                if (added.ProfessionalBodyId < 1)
                {
                    response.Status.Message.FriendlyMessage =
                        "Error Occurred! Unable to complete your request. Please try again later";
                    response.Status.Message.TechnicalMessage = "Unable to save to database";
                    return(response);
                }
                resetCache();
                response.Status.IsSuccessful = true;
                response.SettingId           = added.ProfessionalBodyId;
            }
            catch (DbEntityValidationException ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            return(response);
        }
Beispiel #25
0
        public string AddPost(PostInfo info, ResourceInfo resource1Info, ResourceInfo resource2Info, List<ContactInfo> lstContacts, bool isPicture, bool isVideo, bool isAudio, bool isWeb)
        {
            try
            {
                if (!String.IsNullOrWhiteSpace(info.Title) && !String.IsNullOrWhiteSpace(info.Caption1) && !String.IsNullOrWhiteSpace(info.Caption2)
                     && !String.IsNullOrWhiteSpace(resource1Info.DataUrl) && info.Duration >= 5 && info.Duration <= 60
                     && (info.IsPublic == true || info.ToContacts == true || (info.ToSelectedContacts == true && lstContacts.Count > 0))
                     && (info.TerritoryId != null || info.IsGlobal == true) && (isPicture || isVideo || isAudio) && (info.CategoryId == 1 || info.CategoryId == 2 || info.CategoryId == 3))
                {
                    PostManager mgr = new PostManager();

                    TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);

                    resource1Info.Data = JsonWebToken.Base64UrlDecode(resource1Info.DataUrl);

                    if (resource2Info != null && !String.IsNullOrWhiteSpace(resource2Info.DataUrl))
                        resource2Info.Data = JsonWebToken.Base64UrlDecode(resource2Info.DataUrl);

                    // Sets user token from cookie
                    info.UserIdf = tokenInfo.Idf;
                    info.EndDate = DateTime.UtcNow.AddMinutes(info.Duration);

                    if (info.IsPublic)
                    {
                        info.ToContacts = false;
                        info.ToSelectedContacts = false;
                    }
                    else if (info.ToContacts)
                    {
                        info.ToSelectedContacts = false;
                        info.IsPublic = false;
                    }
                    else if (info.ToSelectedContacts)
                    {
                        info.IsPublic = false;
                        info.ToContacts = false;
                    }

                    if (isPicture)
                    {
                        isVideo = false;
                        isAudio = false;
                    }
                    else if (isVideo)
                    {
                        isPicture = false;
                        isAudio = false;
                    }
                    else if (isAudio)
                    {
                        isVideo = false;
                        isPicture = false;
                    }

                    EnumPostType postType = isPicture ? EnumPostType.Picture : (isVideo ? EnumPostType.Video : (isAudio ? EnumPostType.Audio : EnumPostType.Picture));

                    var guids = mgr.AddPostImages(resource1Info, resource2Info, tokenInfo.FolderPath, postType);
                    long postId = mgr.AddPost(info, guids[0], guids[1], postType, tokenInfo.FolderPath);
                    if (info.ToSelectedContacts)
                    {
                        List<ContactInfo> lstFilteredContacts = new List<ContactInfo>();
                        ContactManager conMgr = new ContactManager();
                        lstContacts.ForEach(x =>
                        {
                            if (!String.IsNullOrWhiteSpace(x.ContactToken))
                            {
                                try
                                {
                                    TokenInfo contactToken = JsonWebToken.DecodeToken<TokenInfo>(x.ContactToken, CodeHelper.SecretAccessKey, true, false);
                                    x.ContactIdf = contactToken.Idf;
                                    lstFilteredContacts.Add(x);
                                }
                                catch (Exception)
                                {
                                    // if contact does not have all details, ignore it
                                }
                            }

                        });
                        conMgr.SavePostContacts(info.UserIdf, info.TerritoryId, info.IsGlobal, postId, lstFilteredContacts);
                    }

                    // schedule job
                    mgr.SchedulePost(postId, info.EndDate);

                    // send notification to all users either GCM or SignalR stating your contact has posted something
                    var obj = GlobalHost.ConnectionManager.GetHubContext<HeyVoteHub>();
                    new PostManager().GetNotificationUserList(postId.ToString()).ForEach(x =>
                    {
                        var signalR = HeyVoteHub.MyUsers.Where(y => y.Value.Equals(x.NotifyUserIdf)).FirstOrDefault();
                        if (!signalR.Equals(default(KeyValuePair<string, string>)))
                            obj.Clients.Client(signalR.Key).notifyUsers(new
                            {
                                Id = x.Id,
                                Title = x.Title,
                                UserIdf = x.UserIdf,
                                ImageIdf = x.ImageIdf,
                                Image1Idf = x.Image1Idf,
                                FolderPath = x.FolderPath,
                                CreatedOn = x.CreatedOn,
                                Caption1 = x.Caption1,
                                Caption2 = x.Caption2,
                                DisplayName = x.DisplayName,
                                PostId = x.PostId,
                                EndDate = x.EndDate,
                                isPost = x.isPost,
                                isFollow = x.isFollow,
                                isContact = x.isContact,
                                hasRead = false,
                                isViewed = false
                            });
                    });

                    return true.ToString();
                }
                return false.ToString();
            }
            catch (Exception ex)
            {
                throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
            }
        }
        public string Execute()
        {
            Console.WriteLine("Please enter the name of the team responsible for the workitem whose status you want to change:");
            Console.WriteLine("List of teams:" + Environment.NewLine + HelperMethods.ListTeams(this.engine.Teams));
            string teamName     = Console.ReadLine();
            bool   ifTeamExists = HelperMethods.IfExists(teamName, engine.Teams);

            if (ifTeamExists == false)
            {
                return("Team with such name does not exist.");
            }
            ITeam team = HelperMethods.ReturnExisting(teamName, engine.Teams);

            Console.Clear();
            Console.WriteLine("Please enter board where the workitem features:");
            Console.WriteLine("List of boards:" + Environment.NewLine + HelperMethods.ListBoards(team.Boards));
            string boardName     = Console.ReadLine();
            bool   ifBoardExists = HelperMethods.IfExists(boardName, team.Boards);

            if (ifBoardExists == false)
            {
                return($"Board with name {boardName} does not exist in team {team.Name}.");
            }
            IBoard board = HelperMethods.ReturnExisting(boardName, team.Boards);

            Console.Clear();
            Console.WriteLine("Please enter the id of the workitem that you wish to change:");
            Console.WriteLine($"List of workitems in team {board.Name}:" + Environment.NewLine + HelperMethods.ListWorkItems(board.WorkItems));
            int  workItemID       = int.Parse(Console.ReadLine());
            bool ifWorkItemExists = HelperMethods.IfExists(workItemID, board.WorkItems);

            if (ifWorkItemExists == false)
            {
                return($"WorkItem with id {workItemID} does not exist in board {board.Name}.");
            }
            IWorkItem workItem = HelperMethods.ReturnExisting(workItemID, board.WorkItems);
            string    result   = "";

            if (workItem is IBug)
            {
                Console.Clear();
                IBug bug = workItem as IBug;
                Console.WriteLine($"Please choose new status of the bug:{Environment.NewLine}" +
                                  $"Type 1 for Active.{Environment.NewLine}" +
                                  $"Type 2 for Fixed.{Environment.NewLine}");
                Console.WriteLine($"The current status of {bug.Title} is: {bug.Status}");
                string    bugStatusUserInput = Console.ReadLine();
                BugStatus status;
                switch (bugStatusUserInput)
                {
                case "1": status = BugStatus.Active; break;

                case "2": status = BugStatus.Fixed; break;

                default: return("invalid command");
                }
                if (status == bug.Status)
                {
                    return($"The selected WorkItem is already classified with status {status}.");
                }
                result     = HelperMethods.TimeStamp() + $"WorkItem with id {bug.ID} changed it's status to {status}.";
                bug.Status = status;
                bug.History.Add(result);
            }

            if (workItem is IStory)
            {
                Console.Clear();
                IStory story = workItem as IStory;
                Console.WriteLine($"Please choose new status of the story:{Environment.NewLine}" +
                                  $"Type 1 for NotDone.{Environment.NewLine}" +
                                  $"Type 2 for InProgress.{Environment.NewLine}" +
                                  $"Type 3 for Done.{Environment.NewLine}");
                Console.WriteLine($"The current status of {story.Title} is: {story.Status}");
                string      storyStatusUserInput = Console.ReadLine();
                StoryStatus status;
                switch (storyStatusUserInput)
                {
                case "1": status = StoryStatus.NotDone; break;

                case "2": status = StoryStatus.InProgress; break;

                case "3": status = StoryStatus.Done; break;

                default: return("invalid command");
                }
                if (status == story.Status)
                {
                    return($"The selected WorkItem is already classified with status {status}.");
                }
                result       = HelperMethods.TimeStamp() + $"WorkItem with id {story.ID} changed it's status to {status}.";
                story.Status = status;
                story.History.Add(result);
            }

            if (workItem is IFeedback)
            {
                Console.Clear();
                IFeedback feedback = workItem as IFeedback;
                Console.WriteLine($"Please choose new status of the feedback:{Environment.NewLine}" +
                                  $"Type 1 for New.{Environment.NewLine}" +
                                  $"Type 2 for Unscheduled.{Environment.NewLine}" +
                                  $"Type 3 for Scheduled.{Environment.NewLine}" +
                                  $"Type 4 for Done.{Environment.NewLine}");
                Console.WriteLine($"The current status of {feedback.Title} is: {feedback.Status}");
                string         feedbackStatusUserInput = Console.ReadLine();
                FeedbackStatus status;
                switch (feedbackStatusUserInput)
                {
                case "1": status = FeedbackStatus.New; break;

                case "2": status = FeedbackStatus.Unscheduled; break;

                case "3": status = FeedbackStatus.Scheduled; break;

                case "4": status = FeedbackStatus.Done; break;

                default: return("invalid command");
                }
                if (status == feedback.Status)
                {
                    return($"The selected WorkItem is already classified with status {status}.");
                }
                result          = HelperMethods.TimeStamp() + $"WorkItem with id {feedback.ID} changed it's status to {status}.";
                feedback.Status = status;
                feedback.History.Add(result);
            }
            if (workItem is IAssignableItem)
            {
                foreach (var item in team.Members)
                {
                    if (item.WorkItems.Contains(workItem))
                    {
                        item.History.Add(result);
                        break;
                    }
                }
            }
            board.History.Add(result);
            team.History.Add(result);
            return(result);
        }
Beispiel #27
0
 /// <summary>
 /// Returns basic profile picture and name by using token
 /// </summary>
 /// <returns></returns>
 public BasicUserInfo GetBasicProfileData(bool isWeb)
 {
     try
     {
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return new UserManager().GetUserInfo(tokenInfo.Idf);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #28
0
        public StoreSetupMasterDataViewModel GetAllMasterDataForStore()
        {
            StoreSetupMasterDataViewModel storeSetupMasterDataViewModel = new StoreSetupMasterDataViewModel();
            List <Country> countryList = new List <Country>();
            List <Model.Entity.TimeZone>     timeZoneList = new List <Model.Entity.TimeZone>();
            List <DisplayPrice>              priceList    = new List <Model.Entity.DisplayPrice>();
            List <UserSwitchingSecurityType> usstList     = new List <Model.Entity.UserSwitchingSecurityType>();
            List <Currency>          currencyList         = new List <Model.Entity.Currency>();
            List <SKUGenerationType> skuList = new List <Model.Entity.SKUGenerationType>();

            using (var command = _dataBaseRepository.db.GetStoredProcCommand(Constants.UspGetAllMasterDataForStore))
            {
                using (var dataReader = _dataBaseRepository.db.ExecuteReader(command))
                {
                    // Get country
                    while (dataReader.Read())
                    {
                        Country country = new Country
                        {
                            CountryId = HelperMethods.GetDataValue <int>(dataReader, "CountryId"),
                            Name      = HelperMethods.GetDataValue <string>(dataReader, "CountryName")
                        };
                        countryList.Add(country);
                    }
                    //Get Time Zone
                    if (dataReader.NextResult())
                    {
                        while (dataReader.Read())
                        {
                            Model.Entity.TimeZone timeZone = new Model.Entity.TimeZone
                            {
                                TimeZoneId   = HelperMethods.GetDataValue <int>(dataReader, "TimeZoneId"),
                                DsiplayName  = HelperMethods.GetDataValue <string>(dataReader, "DsiplayName"),
                                StandardName = HelperMethods.GetDataValue <string>(dataReader, "StandardName")
                            };
                            timeZoneList.Add(timeZone);
                        }
                    }
                    // GET Price
                    if (dataReader.NextResult())
                    {
                        while (dataReader.Read())
                        {
                            Model.Entity.DisplayPrice price = new Model.Entity.DisplayPrice
                            {
                                DisplayPriceId   = HelperMethods.GetDataValue <int>(dataReader, "DisplayPriceId"),
                                DisplayPriceName = HelperMethods.GetDataValue <string>(dataReader, "DisplayPriceName")
                            };
                            priceList.Add(price);
                        }
                    }

                    // GET UserSwitchingSecurityType
                    if (dataReader.NextResult())
                    {
                        while (dataReader.Read())
                        {
                            Model.Entity.UserSwitchingSecurityType usst = new Model.Entity.UserSwitchingSecurityType
                            {
                                UserSwitchingSecurityTypeId   = HelperMethods.GetDataValue <int>(dataReader, "UserSwitchingSecurityTypeId"),
                                UserSwitchingSecurityTypeName = HelperMethods.GetDataValue <string>(dataReader, "UserSwitchingSecurityTypeName")
                            };
                            usstList.Add(usst);
                        }
                    }

                    // GET UserSwitchingSecurityType
                    if (dataReader.NextResult())
                    {
                        while (dataReader.Read())
                        {
                            Model.Entity.SKUGenerationType sku = new Model.Entity.SKUGenerationType
                            {
                                SKUGenerationTypeId = HelperMethods.GetDataValue <int>(dataReader, "SKUGenerationTypeId"),
                                SKUGenerationName   = HelperMethods.GetDataValue <string>(dataReader, "SKUGenerationName")
                            };
                            skuList.Add(sku);
                        }
                    }

                    // GET Currency
                    if (dataReader.NextResult())
                    {
                        while (dataReader.Read())
                        {
                            Model.Entity.Currency currency = new Model.Entity.Currency
                            {
                                CurrencyId     = HelperMethods.GetDataValue <int>(dataReader, "CurrencyId"),
                                CurrencyName   = HelperMethods.GetDataValue <string>(dataReader, "CurrencyName"),
                                CurrencySymbol = HelperMethods.GetDataValue <string>(dataReader, "CurrencySymbol")
                            };
                            currencyList.Add(currency);
                        }
                    }
                }
            }

            storeSetupMasterDataViewModel.Country      = countryList;
            storeSetupMasterDataViewModel.TimeZone     = timeZoneList;
            storeSetupMasterDataViewModel.DisplayPrice = priceList;
            storeSetupMasterDataViewModel.UserSwitchingSecurityType = usstList;
            storeSetupMasterDataViewModel.Currency          = currencyList;
            storeSetupMasterDataViewModel.SKUGenerationType = skuList;

            return(storeSetupMasterDataViewModel);
        }
Beispiel #29
0
        public ActionResult <GenericResponseModel> Insert([FromBody] AssetDto pObject)
        {
            var loUserId          = HelperMethods.GetApiUserIdFromToken(HttpContext.User.Identity);
            var loGenericResponse = new GenericResponseModel
            {
                Status = "Fail",
                Code   = -1
            };

            if (pObject.asset_photos == null || !pObject.asset_photos.Any())
            {
                loGenericResponse.Status  = "Fail";
                loGenericResponse.Code    = -1;
                loGenericResponse.Message = "Gayrimenkul fotoğraflarında bir problem oldu!. Tekrar yükleme yapın!";
                return(loGenericResponse);
            }

            pObject.row_create_date = DateTime.Now;
            pObject.row_create_user = loUserId;
            pObject.row_guid        = Guid.NewGuid();
            pObject.is_deleted      = false;
            pObject.is_active       = true;
            pObject.city            = pObject.city.ToUpper();
            pObject.district        = pObject.district?.ToUpper();
            pObject.address         = pObject.address?.ToUpper();
            pObject.share           = pObject.share?.ToUpper();
            pObject.asset_name      = pObject.asset_name?.ToUpper();
            pObject.asset_no        = pObject.asset_no?.ToUpper();

            if (pObject.registry_price == null)
            {
                pObject.registry_price = 0;
            }

            if (pObject.free_text_no == null)
            {
                pObject.free_text_no = "";
            }

            if (pObject.first_announcement_date == null)
            {
                if (DateTime.TryParse(pObject.first_announcement_date_str, out var loFirstAnnonce))
                {
                    pObject.first_announcement_date = loFirstAnnonce;
                }
                else
                {
                    loGenericResponse.Status  = "Fail";
                    loGenericResponse.Code    = -1;
                    loGenericResponse.Message = "İlan yayın başlangıç tarihi girilmeden işleme devam edilemez.";
                    return(loGenericResponse);
                }

                if (DateTime.Now > pObject.first_announcement_date.Value && DateTime.Now.ToShortDateString() != pObject.first_announcement_date.Value.ToShortDateString())
                {
                    loGenericResponse.Status  = "Fail";
                    loGenericResponse.Code    = -1;
                    loGenericResponse.Message = "Geçmiş tarihili ilan başlatılamaz.";
                    return(loGenericResponse);
                }
            }

            if (pObject.last_announcement_date == null)
            {
                if (DateTime.TryParse(pObject.last_announcement_date_str, out var loLastAnnonce))
                {
                    pObject.last_announcement_date = loLastAnnonce;
                }
                else
                {
                    loGenericResponse.Status  = "Fail";
                    loGenericResponse.Code    = -1;
                    loGenericResponse.Message = "İlan yayın bitiş tarihi girilmeden işleme devam edilemez.";
                    return(loGenericResponse);
                }

                if (pObject.last_announcement_date < pObject.first_announcement_date)
                {
                    loGenericResponse.Status  = "Fail";
                    loGenericResponse.Code    = -1;
                    loGenericResponse.Message = "İlanın bitiş tarihi başlangıç tarihinden önce olamaz";
                    return(loGenericResponse);
                }
            }

            if (pObject.last_offer_date == null)
            {
                if (DateTime.TryParse(pObject.last_offer_date_str, out var loOffer))
                {
                    pObject.last_offer_date = loOffer;
                }
                else
                {
                    loGenericResponse.Status  = "Fail";
                    loGenericResponse.Code    = -1;
                    loGenericResponse.Message = "İlan son teklif tarihi girilmeden işleme devam edilemez.";
                    return(loGenericResponse);
                }

                if (pObject.last_offer_date < pObject.last_announcement_date)
                {
                    loGenericResponse.Status  = "Fail";
                    loGenericResponse.Code    = -1;
                    loGenericResponse.Message = "Son teklif tarihi, ilan bitiş tarihinden önce olamaz";
                    return(loGenericResponse);
                }
            }

            var loResult = Crud <AssetDto> .InsertAsset(pObject);

            if (loResult > 0)
            {
                pObject.id               = loResult;
                loGenericResponse.Data   = pObject;
                loGenericResponse.Status = "Ok";
                loGenericResponse.Code   = 200;
            }
            else
            {
                loGenericResponse.Status  = "Fail";
                loGenericResponse.Code    = -1;
                loGenericResponse.Message = "Gayrimenkul kaydı başarısız";
            }

            return(loGenericResponse);
        }
Beispiel #30
0
        public static void Main()
        {
            HelperMethods.DisplayTaskDescription(Constants.PathToTaskDescription);

            TestFirstBeforeLast();
        }
 protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
 {
     HelperMethods.DisableBackButton();
 }
Beispiel #32
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Default logger.  Currently, uses the Trace class (i.e. sends events
        /// to the current trace listeners, if any).
        /// </summary>
        /// <param name="sender">Should be null.</param>
        /// <param name="e">The data associated with this event.</param>
        private static void LogEventHandler(
            object sender,
            LogEventArgs e
            )
        {
#if !NET_COMPACT_20
            if (e == null)
            {
                return;
            }

            string message = e.Message;

            if (message == null)
            {
                message = "<null>";
            }
            else
            {
                message = message.Trim();

                if (message.Length == 0)
                {
                    message = "<empty>";
                }
            }

            object errorCode = e.ErrorCode;
            string type      = "error";

            if ((errorCode is SQLiteErrorCode) || (errorCode is int))
            {
                SQLiteErrorCode rc = (SQLiteErrorCode)(int)errorCode;

                rc &= SQLiteErrorCode.NonExtendedMask;

                if (rc == SQLiteErrorCode.Ok)
                {
                    type = "message";
                }
                else if (rc == SQLiteErrorCode.Notice)
                {
                    type = "notice";
                }
                else if (rc == SQLiteErrorCode.Warning)
                {
                    type = "warning";
                }
                else if ((rc == SQLiteErrorCode.Row) ||
                         (rc == SQLiteErrorCode.Done))
                {
                    type = "data";
                }
            }
            else if (errorCode == null)
            {
                type = "trace";
            }

            if ((errorCode != null) &&
                !Object.ReferenceEquals(errorCode, String.Empty))
            {
                Trace.WriteLine(HelperMethods.StringFormat(
                                    CultureInfo.CurrentCulture, "SQLite {0} ({1}): {2}",
                                    type, errorCode, message));
            }
            else
            {
                Trace.WriteLine(HelperMethods.StringFormat(
                                    CultureInfo.CurrentCulture, "SQLite {0}: {1}",
                                    type, message));
            }
#endif
        }
        public static HybridCrmConnection CreateAdminConnectionFromAppConfig()
        {
            var clientId     = HelperMethods.GetAppSettingsValue("AdminClientId", true) ?? HelperMethods.GetAppSettingsValue("ClientId");
            var clientSecret = HelperMethods.GetAppSettingsValue("AdminClientSecret", true) ?? HelperMethods.GetAppSettingsValue("ClientSecret");
            var username     = HelperMethods.GetAppSettingsValue("AdminUsername", true) ?? HelperMethods.GetAppSettingsValue("Username");
            var password     = HelperMethods.GetAppSettingsValue("AdminPassword", true) ?? HelperMethods.GetAppSettingsValue("Password");

            return(new HybridCrmConnection(clientId, clientSecret, username, password));
        }
        public void GetPassportRows()
        {
            IEnumerable <string> lines = HelperMethods.ReadFile("day4-test.txt");

            Assert.Equal(13, lines.Count());
        }
        public static void Main()
        {
            HelperMethods.DisplayTaskDescription(Constants.PathToTaskDescription);

            TestStudentClass();
        }
        /// <summary>
        /// Generate puzzle pieces from image.
        /// </summary>
        /// <param name="NoOfPiecesInRow">Total no of pieces in row of puzzle / total columns</param>
        /// <param name="NoOfPiecesInCol">Total no of pieces in Col of puzzle / total rows</param>
        /// <param name="Image">Main image for puzzle</param>
        /// <param name="JointMaskImage">Mask images for joints to be used to create joints for pieces in this puzzle</param>
        /// <param name="CreatedImageMask">Unknown</param>
        /// <returns>Returns generated pieces metadata</returns>
        private SPieceInfo[,] GenerateJigsawPieces(Texture2D Image, Texture2D[] JointMaskImage, out Texture2D CreatedImageMask, int NoOfPiecesInRow, int NoOfPiecesInCol)
        {
            #region "Argument Error Checking"

            if (NoOfPiecesInRow < 2)
            {
                throw new System.ArgumentOutOfRangeException("NoOfPiecesInRow", "Argument should be greater then 1");
            }
            else if (NoOfPiecesInCol < 2)
            {
                throw new System.ArgumentOutOfRangeException("NoOfPiecesInCol", "Argument should be greater then 1");
            }
            else if (Image == null)
            {
                throw new System.ArgumentNullException("No texture2d assigned to this class");
            }

            #endregion



            _noOfPiecesInRow = NoOfPiecesInRow;
            _noOfPiecesInCol = NoOfPiecesInCol;

            _origionalImage = Image;

            Color[][] _PuzzleImageTopJointMask   = HelperMethods.Texture2DToColorArr(Image);
            Color[][] _PuzzleImageBotJointMask   = HelperMethods.Texture2DToColorArr(Image);
            Color[][] _PuzzleImageLeftJointMask  = HelperMethods.Texture2DToColorArr(Image);
            Color[][] _PuzzleImageRightJointMask = HelperMethods.Texture2DToColorArr(Image);
            Color[][] _PuzzleImage = HelperMethods.Texture2DToColorArr(Image);


            SPieceInfo[,] PiecesInformation = null;


            PiecesInformation = DrawCustomPieceJointsMask(ref _PuzzleImageTopJointMask, ref _PuzzleImageBotJointMask,
                                                          ref _PuzzleImageLeftJointMask, ref _PuzzleImageRightJointMask,
                                                          JointMaskImage, out _pieceWidthWithoutJoint,
                                                          out _pieceHeightWithoutJoint, Image.width, Image.height, NoOfPiecesInCol, NoOfPiecesInRow);



            CreatedImageMask = HelperMethods.ColorArrToTexture2D(_PuzzleImageTopJointMask);

            //Create mask image for each side joints
            JointsMaskToJointsImage(ref _PuzzleImage, ref _PuzzleImageTopJointMask, ref _PuzzleImageBotJointMask,
                                    ref _PuzzleImageLeftJointMask, ref _PuzzleImageRightJointMask,
                                    PieceWidthWithoutJoint, PieceHeightWithoutJoint, Image.width, Image.height);

            _topJointsMaskImage   = HelperMethods.ColorArrToTexture2D(_PuzzleImageTopJointMask);
            _botJointsMaskImage   = HelperMethods.ColorArrToTexture2D(_PuzzleImageBotJointMask);
            _leftJointsMaskImage  = HelperMethods.ColorArrToTexture2D(_PuzzleImageLeftJointMask);
            _rightJointsMaskImage = HelperMethods.ColorArrToTexture2D(_PuzzleImageRightJointMask);

            _image = HelperMethods.ColorArrToTexture2D(_PuzzleImage);


            //Return data for puzzle pieces
            SPieceInfo[,] ResultData = new SPieceInfo[NoOfPiecesInCol, NoOfPiecesInRow];
            for (int i = 0; i < NoOfPiecesInCol; i++)
            {
                for (int j = 0; j < NoOfPiecesInRow; j++)
                {
                    ResultData[i, j] = PiecesInformation[i, j];
                }
            }

            return(ResultData);
        }
Beispiel #37
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Variables
            List <string>                names = new List <string>();
            List <RobotJointPosition>    robotJointPositions    = new List <RobotJointPosition>();
            List <ExternalJointPosition> externalJointPositions = new List <ExternalJointPosition>();

            // Catch input data
            if (!DA.GetDataList(0, names))
            {
                return;
            }
            if (!DA.GetDataList(1, robotJointPositions))
            {
                robotJointPositions = new List <RobotJointPosition>()
                {
                    new RobotJointPosition()
                };
            }
            if (!DA.GetDataList(2, externalJointPositions))
            {
                externalJointPositions = new List <ExternalJointPosition>()
                {
                    new ExternalJointPosition()
                };
            }

            // Replace spaces
            names = HelperMethods.ReplaceSpacesAndRemoveNewLines(names);

            // Get longest input List
            int[] sizeValues = new int[3];
            sizeValues[0] = names.Count;
            sizeValues[1] = robotJointPositions.Count;
            sizeValues[2] = externalJointPositions.Count;

            int biggestSize = HelperMethods.GetBiggestValue(sizeValues);

            // Keeps track of used indicies
            int nameCounter   = -1;
            int robPosCounter = -1;
            int extPosCounter = -1;

            // Clear list
            _jointTargets.Clear();

            // Creates the joint targets
            for (int i = 0; i < biggestSize; i++)
            {
                string                name;
                RobotJointPosition    robotJointPosition;
                ExternalJointPosition externalJointPosition;

                // Names counter
                if (i < sizeValues[0])
                {
                    name = names[i];
                    nameCounter++;
                }
                else
                {
                    name = names[nameCounter] + "_" + (i - nameCounter);
                }

                // Robot Joint Position counter
                if (i < sizeValues[1])
                {
                    robotJointPosition = robotJointPositions[i];
                    robPosCounter++;
                }
                else
                {
                    robotJointPosition = robotJointPositions[robPosCounter];
                }

                // External Joint Position counter
                if (i < sizeValues[2])
                {
                    externalJointPosition = externalJointPositions[i];
                    extPosCounter++;
                }
                else
                {
                    externalJointPosition = externalJointPositions[extPosCounter];
                }

                JointTarget jointTarget = new JointTarget(name, robotJointPosition, externalJointPosition);
                _jointTargets.Add(jointTarget);
            }

            // Sets Output
            DA.SetDataList(0, _jointTargets);

            #region Object manager
            // Gets ObjectManager of this document
            _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument());

            // Clears targetNames
            for (int i = 0; i < _targetNames.Count; i++)
            {
                _objectManager.TargetNames.Remove(_targetNames[i]);
            }
            _targetNames.Clear();

            // Removes lastName from targetNameList
            if (_objectManager.TargetNames.Contains(_lastName))
            {
                _objectManager.TargetNames.Remove(_lastName);
            }

            // Adds Component to TargetByGuid Dictionary
            if (!_objectManager.OldJointTargetsByGuid3.ContainsKey(this.InstanceGuid))
            {
                _objectManager.OldJointTargetsByGuid3.Add(this.InstanceGuid, this);
            }

            // Checks if target name is already in use and counts duplicates
            #region Check name in object manager
            _namesUnique = true;
            for (int i = 0; i < names.Count; i++)
            {
                if (_objectManager.TargetNames.Contains(names[i]))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name already in use.");
                    _namesUnique = false;
                    _lastName    = "";
                    break;
                }
                else
                {
                    // Adds Target Name to list
                    _targetNames.Add(names[i]);
                    _objectManager.TargetNames.Add(names[i]);

                    // Run SolveInstance on other Targets with no unique Name to check if their name is now available
                    _objectManager.UpdateTargets();

                    _lastName = names[i];
                }

                // Checks if variable name exceeds max character limit for RAPID Code
                if (HelperMethods.VariableExeedsCharacterLimit32(names[i]))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name exceeds character limit of 32 characters.");
                    break;
                }

                // Checks if variable name starts with a number
                if (HelperMethods.VariableStartsWithNumber(names[i]))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name starts with a number which is not allowed in RAPID Code.");
                    break;
                }
            }
            #endregion

            // Recognizes if Component is Deleted and removes it from Object Managers target and name list
            GH_Document doc = this.OnPingDocument();
            if (doc != null)
            {
                doc.ObjectsDeleted += DocumentObjectsDeleted;
            }
            #endregion
        }
        /// <summary>
        /// Draws joint mask image for each side of joints for every piece which is used to later
        /// generate puzzle image for pieces
        /// </summary>
        /// <param name="TopJointMaskImage">Output mask image for top joints</param>
        /// <param name="BotJointMaskImage">Output mask image for bottom joints</param>
        /// <param name="LeftJointMaskImage">Output mask image for left joints</param>
        /// <param name="RightJointMaskImage">Output mask image for right joints</param>
        /// <param name="JointMaskImages">User provided joint mask images to be used</param>
        /// <param name="PieceHeightWithoutJoint">Output piece image height</param>
        /// <param name="PieceWidthWithoutJoint">Output piece image width</param>
        /// <param name="PuzzleImgHeight">Height of user provided puzzle image</param>
        /// <param name="PuzzleImgWidth">Width of user provided puzzle image</param>
        /// <param name="Cols">Total columns in puzzle</param>
        /// <param name="Rows">Total rows in puzzle</param>
        /// <returns>Returns created pieces metadata created during masks creation</returns>
        private SPieceInfo[,] DrawCustomPieceJointsMask(ref Color[][] TopJointMaskImage, ref Color[][] BotJointMaskImage,
                                                        ref Color[][] LeftJointMaskImage, ref Color[][] RightJointMaskImage, Texture2D[] JointMaskImages,
                                                        out int PieceWidthWithoutJoint, out int PieceHeightWithoutJoint, int PuzzleImgWidth, int PuzzleImgHeight, int Rows = 5, int Cols = 5)
        {
            int[] JointMaskWidth  = new int[JointMaskImages.Length];
            int[] JointMaskHeight = new int[JointMaskImages.Length];

            //Create direction wise mask images
            Texture2D[] LeftJointMask   = new Texture2D[JointMaskImages.Length];
            Texture2D[] RightJointMask  = new Texture2D[JointMaskImages.Length];
            Texture2D[] TopJointMask    = new Texture2D[JointMaskImages.Length];
            Texture2D[] BottomJointMask = new Texture2D[JointMaskImages.Length];

            SPieceInfo[,] ResultPiecesData = new SPieceInfo[Rows, Cols];


            //Initialize pieces data
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    ResultPiecesData[i, j] = new SPieceInfo((i * Cols) + j);
                }
            }

            int PieceHeight = PuzzleImgHeight / Rows;
            int PieceWidth  = PuzzleImgWidth / Cols;

            PieceWidthWithoutJoint  = PieceWidth;
            PieceHeightWithoutJoint = PieceHeight;



            for (int ArrayTav = 0; ArrayTav < JointMaskImages.Length; ArrayTav++)
            {
                LeftJointMask[ArrayTav]   = JointMaskImages[ArrayTav];
                BottomJointMask[ArrayTav] = HelperMethods.rotateImage(JointMaskImages[ArrayTav], 90);
                RightJointMask[ArrayTav]  = HelperMethods.rotateImage(BottomJointMask[ArrayTav], 90);
                TopJointMask[ArrayTav]    = HelperMethods.rotateImage(JointMaskImages[ArrayTav], 270);


                #region "Resize Joint mask images for drawing inside mask image And calculate joints width and height"

                //Resize Joint mask images for drawing inside mask image
                //  Image will be resized according to piece width
                int MaskImageWidth  = (int)(PieceWidth * 0.3f);
                int MaskImageHeight = (int)((float)MaskImageWidth / ((float)JointMaskImages[ArrayTav].width / (float)JointMaskImages[ArrayTav].height));

                LeftJointMask[ArrayTav]   = HelperMethods.resizeImage(LeftJointMask[ArrayTav], MaskImageWidth, MaskImageHeight);
                RightJointMask[ArrayTav]  = HelperMethods.resizeImage(RightJointMask[ArrayTav], MaskImageWidth, MaskImageHeight);
                TopJointMask[ArrayTav]    = HelperMethods.resizeImage(TopJointMask[ArrayTav], MaskImageWidth, MaskImageHeight);
                BottomJointMask[ArrayTav] = HelperMethods.resizeImage(BottomJointMask[ArrayTav], MaskImageWidth, MaskImageHeight);


                //Calculate joints width and heights
                CalculateCustomJointDimensions(LeftJointMask[ArrayTav], out JointMaskWidth[ArrayTav], out JointMaskHeight[ArrayTav]);



                #endregion
            }



            #region "Argument Error Checking"

            //Joint mask image width and height should be same
            //Joint mask image should have only black and white pixels inside it

            if (JointMaskImages[0].width != JointMaskImages[0].height)
            {
                Debug.LogError("JointMaskImage width and height should be same");
                return(null);
            }
            else
            {
                bool ErrorFound = false;  //If Non-Black or Non-White pixel found

                //Check for pixel colors in joint mask image
                for (int rowtrav = 0; rowtrav < JointMaskImages[0].height && !ErrorFound; rowtrav++)
                {
                    for (int coltrav = 0; coltrav < JointMaskImages[0].width && !ErrorFound; coltrav++)
                    {
                        Color PixelColor = JointMaskImages[0].GetPixel(coltrav, rowtrav);

                        if (PixelColor != Color.white || PixelColor != Color.black)
                        {
                            ErrorFound = true;

                            //Debug.LogError("Only white and black pixels are allowed in JointMaskImage");

                            //return null;
                        }
                    }
                }
            }

            #endregion

            TopJointMaskImage   = new Color[PuzzleImgWidth][];
            BotJointMaskImage   = new Color[PuzzleImgWidth][];
            LeftJointMaskImage  = new Color[PuzzleImgWidth][];
            RightJointMaskImage = new Color[PuzzleImgWidth][];

            //Clear Instantiated mask image
            for (int i = 0; i < PuzzleImgWidth; i++)
            {
                TopJointMaskImage[i]   = new Color[PuzzleImgHeight];
                BotJointMaskImage[i]   = new Color[PuzzleImgHeight];
                LeftJointMaskImage[i]  = new Color[PuzzleImgHeight];
                RightJointMaskImage[i] = new Color[PuzzleImgHeight];
            }


            //Generate random joint info And Draw joints

            Random.seed = System.DateTime.Now.Second;
            Color PieceColor = Color.black;


            for (int RowTrav = 0; RowTrav < Rows; RowTrav++)
            {
                for (int ColTrav = 0; ColTrav < Cols; ColTrav++)
                {
                    int PieceX = ColTrav * PieceWidth;
                    int PieceY = RowTrav * PieceHeight;

                    //Generate Random joint info and Draw Joints From Mask Image

                    #region "Draw right joints according to piece joint information"

                    if (ColTrav < Cols - 1)
                    {
                        int SelectedRandomJoint = Random.Range(1, JointMaskImages.Length) - 1;

                        //Create random joint information
                        int RndVal = (int)(Random.Range(1f, 18f) >= 10 ? 1 : 0);
                        ResultPiecesData[RowTrav, ColTrav].AddJoint(new SJointInfo((EJointType)RndVal, EJointPosition.Right,
                                                                                   JointMaskWidth[SelectedRandomJoint], JointMaskHeight[SelectedRandomJoint]));


                        int JointX = PieceX + PieceWidth;
                        int JointY = PieceY + (PieceHeight / 2) - (RightJointMask[SelectedRandomJoint].height / 2);

                        bool       Result         = false;
                        SJointInfo RightJointInfo = ResultPiecesData[RowTrav, ColTrav].GetJoint(EJointPosition.Right, out Result);

                        if (!Result)
                        {
                            Debug.LogError("Logical error in draw joints from mask image Right Joints");
                        }
                        else
                        {
                            if (RightJointInfo.JointType == EJointType.Male)
                            {
                                drawJoint(ref RightJointMaskImage, RightJointMask[SelectedRandomJoint], PieceColor, JointX, JointY);
                            }
                        }
                    }
                    #endregion

                    #region "Draw left joints according to piece joint information"

                    if (ColTrav > 0)
                    {
                        int SelectedRandomJoint = Random.Range(1, JointMaskImages.Length) - 1;

                        //Create random joint information
                        bool Result = false;

                        SJointInfo PreviousRightJoint = ResultPiecesData[RowTrav, ColTrav - 1].GetJoint(EJointPosition.Right, out Result);

                        if (Result == false)
                        {
                            Debug.LogError("Logical error in joints information left joint");
                        }
                        else
                        {
                            SJointInfo CalcLeftJoint = new SJointInfo(PreviousRightJoint.JointType == EJointType.Female ?
                                                                      EJointType.Male : EJointType.Female, EJointPosition.Left,
                                                                      JointMaskWidth[SelectedRandomJoint], JointMaskHeight[SelectedRandomJoint]);
                            ResultPiecesData[RowTrav, ColTrav].AddJoint(CalcLeftJoint);
                        }


                        int JointX = PieceX - LeftJointMask[SelectedRandomJoint].width;
                        int JointY = PieceY + (PieceHeight / 2) - (LeftJointMask[SelectedRandomJoint].height / 2);

                        Result = false;
                        SJointInfo LeftJointInfo = ResultPiecesData[RowTrav, ColTrav].GetJoint(EJointPosition.Left, out Result);

                        if (!Result)
                        {
                            Debug.LogError("Logical error in draw joints from mask image Left Joints");
                        }
                        else
                        {
                            if (LeftJointInfo.JointType == EJointType.Male)
                            {
                                drawJoint(ref LeftJointMaskImage, LeftJointMask[SelectedRandomJoint], PieceColor, JointX, JointY);
                            }
                        }
                    }

                    #endregion

                    #region "Draw Top joints according to piece joint information"

                    if (RowTrav < Rows - 1)
                    {
                        int SelectedRandomJoint = Random.Range(1, JointMaskImages.Length) - 1;

                        //Create random joint information
                        int RndVal = (int)(Random.Range(1f, 17f) >= 10 ? 1 : 0);
                        ResultPiecesData[RowTrav, ColTrav].AddJoint(new SJointInfo((EJointType)RndVal, EJointPosition.Top,
                                                                                   JointMaskWidth[SelectedRandomJoint], JointMaskHeight[SelectedRandomJoint]));

                        int JointX = PieceX + (PieceWidth / 2) - (TopJointMask[SelectedRandomJoint].width / 2);
                        int JointY = PieceY + PieceHeight;

                        bool       Result       = false;
                        SJointInfo TopJointInfo = ResultPiecesData[RowTrav, ColTrav].GetJoint(EJointPosition.Top, out Result);

                        if (!Result)
                        {
                            Debug.LogError("Logical error in draw joints from mask image Top Joints");
                        }
                        else
                        {
                            if (TopJointInfo.JointType == EJointType.Male)
                            {
                                drawJoint(ref TopJointMaskImage, TopJointMask[SelectedRandomJoint], PieceColor, JointX, JointY);
                            }
                        }
                    }

                    #endregion

                    #region "Draw Bottom joints according to piece joint information"

                    if (RowTrav > 0)
                    {
                        int SelectedRandomJoint = Random.Range(1, JointMaskImages.Length) - 1;

                        //Create random joint information
                        bool Result = false;

                        SJointInfo PreviousPieceTopJoint = ResultPiecesData[RowTrav - 1, ColTrav].GetJoint(EJointPosition.Top, out Result);

                        if (Result == false)
                        {
                            Debug.LogError("Logical error in joints information Bottom joint");
                        }
                        else
                        {
                            SJointInfo CalcBottomJoint = new SJointInfo(PreviousPieceTopJoint.JointType == EJointType.Female ?
                                                                        EJointType.Male : EJointType.Female, EJointPosition.Bottom,
                                                                        JointMaskWidth[SelectedRandomJoint], JointMaskHeight[SelectedRandomJoint]);

                            ResultPiecesData[RowTrav, ColTrav].AddJoint(CalcBottomJoint);
                        }


                        int JointX = PieceX + (PieceWidth / 2) - (BottomJointMask[SelectedRandomJoint].width / 2);
                        int JointY = PieceY - BottomJointMask[SelectedRandomJoint].height;

                        Result = false;
                        SJointInfo BottomJointInfo = ResultPiecesData[RowTrav, ColTrav].GetJoint(EJointPosition.Bottom, out Result);

                        if (!Result)
                        {
                            Debug.LogError("Logical error in draw joints from mask image Top Joints");
                        }
                        else
                        {
                            if (BottomJointInfo.JointType == EJointType.Male)
                            {
                                drawJoint(ref BotJointMaskImage, BottomJointMask[SelectedRandomJoint], PieceColor, JointX, JointY);
                            }
                        }
                    }

                    #endregion
                }
            }



            return(ResultPiecesData);
        }
Beispiel #39
0
        public SettingRegRespObj AddQualification(RegQualificationObj regObj)
        {
            var response = new SettingRegRespObj
            {
                Status = new APIResponseStatus
                {
                    IsSuccessful = false,
                    Message      = new APIResponseMessage()
                }
            };

            try
            {
                if (regObj.Equals(null))
                {
                    response.Status.Message.FriendlyMessage  = "Error Occurred! Unable to proceed with your request";
                    response.Status.Message.TechnicalMessage = "Registration Object is empty / invalid";
                    return(response);
                }

                if (!EntityValidatorHelper.Validate(regObj, out var valResults))
                {
                    var errorDetail = new StringBuilder();
                    if (!valResults.IsNullOrEmpty())
                    {
                        errorDetail.AppendLine("Following error occurred:");
                        valResults.ForEachx(m => errorDetail.AppendLine(m.ErrorMessage));
                    }

                    else
                    {
                        errorDetail.AppendLine(
                            "Validation error occurred! Please check all supplied parameters and try again");
                    }
                    response.Status.Message.FriendlyMessage  = errorDetail.ToString();
                    response.Status.Message.TechnicalMessage = errorDetail.ToString();
                    response.Status.IsSuccessful             = false;
                    return(response);
                }

                if (!HelperMethods.IsUserValid(regObj.AdminUserId, regObj.SysPathCode,
                                               HelperMethods.getSeniorAccountant(), ref response.Status.Message))
                {
                    return(response);
                }

                if (IsQualificationDuplicate(regObj.Name, 1, ref response))
                {
                    return(response);
                }

                var qualification = new Qualification
                {
                    Name   = regObj.Name,
                    Rank   = regObj.Rank,
                    Status = (ItemStatus)regObj.Status
                };

                var added = _repository.Add(qualification);

                _uoWork.SaveChanges();

                if (added.QualificationId < 1)
                {
                    response.Status.Message.FriendlyMessage =
                        "Error Occurred! Unable to complete your request. Please try again later";
                    response.Status.Message.TechnicalMessage = "Unable to save to database";
                    return(response);
                }
                resetCache();
                response.Status.IsSuccessful = true;
                response.SettingId           = added.QualificationId;
            }
            catch (DbEntityValidationException ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            return(response);
        }
Beispiel #40
0
        public new ActionResult Create(UserModel model, string status, string submitButton)
        {
            //check the other submit buttons and act on them, or continue
            switch (submitButton)
            {
            case "Cancel":
                return(RedirectToAction("Index", "Users"));
            }

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    var usrMgr = new UserFactory();

                    //go get the default password for the current city.
                    var    settings = (new CustomerSettingsFactory()).Get("DefaultPassword", CurrentCity.Id);
                    string defaultPassword;
                    if (settings.Any())
                    {
                        defaultPassword = settings[0].Value;
                    }
                    else
                    {
                        ModelState.AddModelError("DefaultPassword", "No default password defined for customer.");
                        model.Groups = GetGroups();
                        return(View(model));
                    }

                    //if the middle name is empty, set it to a default
                    if (string.IsNullOrEmpty(model.MiddleInitial))
                    {
                        model.MiddleInitial = Constants.User.DefaultMiddleName;
                    }

                    //get the phone to empty string, since int he DB it shouldnt be null
                    if (string.IsNullOrEmpty(model.PhoneNumber))
                    {
                        model.PhoneNumber = "";
                    }

                    bool active = status == "Active";
                    //create the user, set their profile information, and add them to the default group for this store
                    string username        = usrMgr.CreateUser(model, CurrentCity.InternalName, defaultPassword, active);
                    var    settingsFactory = new SettingsFactory();
                    int    userId          = usrMgr.GetUserId(model.Username);
                    settingsFactory.Set(userId, Constants.User.IsTechnician, model.IsTechnician.ToString());
                    (new TechnicianFactory()).SetTechnician(model, CurrentCity);
                    return(RedirectToAction("Index", "Users"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", HelperMethods.ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            model.Groups = GetGroups();
            return(View(model));
        }
Beispiel #41
0
        private void SetupInstance(int x = 0, int y = 0, int width = 800, int height = 600)
        {
            IsVisible = true;
            Topmost   = BypassTopmost ? false : true;

            X      = x;
            Y      = y;
            Width  = width;
            Height = height;

            WindowClassName = HelperMethods.GenerateRandomString(5, 11);
            string randomMenuName = HelperMethods.GenerateRandomString(5, 11);

            if (WindowTitle == null)
            {
                WindowTitle = HelperMethods.GenerateRandomString(5, 11);
            }

            // prepare method
            _windowProc = WindowProcedure;
            RuntimeHelpers.PrepareDelegate(_windowProc);
            _windowProcPtr = Marshal.GetFunctionPointerForDelegate(_windowProc);

            WNDCLASSEX wndClassEx = new WNDCLASSEX()
            {
                cbSize        = WNDCLASSEX.Size(),
                style         = 0,
                lpfnWndProc   = _windowProcPtr,
                cbClsExtra    = 0,
                cbWndExtra    = 0,
                hInstance     = IntPtr.Zero,
                hIcon         = IntPtr.Zero,
                hCursor       = IntPtr.Zero,
                hbrBackground = IntPtr.Zero,
                lpszMenuName  = randomMenuName,
                lpszClassName = WindowClassName,
                hIconSm       = IntPtr.Zero
            };

            User32.RegisterClassEx(ref wndClassEx);

            uint exStyle;

            if (BypassTopmost)
            {
                exStyle = 0x20 | 0x80000 | 0x80 | 0x8000000;
            }
            else
            {
                exStyle = 0x8 | 0x20 | 0x80000 | 0x80 | 0x8000000; // WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED |WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE
            }

            WindowHandle = User32.CreateWindowEx(
                exStyle, // WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED |WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE
                WindowClassName,
                WindowTitle,
                0x80000000 | 0x10000000, // WS_POPUP | WS_VISIBLE
                X, Y,
                Width, Height,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero
                );

            User32.SetLayeredWindowAttributes(WindowHandle, 0, 255, /*0x1 |*/ 0x2);
            User32.UpdateWindow(WindowHandle);

            // If window is incompatible on some platforms use SetWindowLong to set the style again
            // and UpdateWindow If you have changed certain window data using SetWindowLong, you must
            // call SetWindowPos for the changes to take effect. Use the following combination for
            // uFlags: SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED.

            ExtendFrameIntoClientArea();
        }
Beispiel #42
0
 public bool ChangeNotificationStatus(long notificationId, bool isWeb)
 {
     try
     {
         PostManager mgr = new PostManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.ChangeNotificationStatus(tokenInfo.Idf, notificationId);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
        public override void Run(List <Point> points, List <Line> lines, List <Polygon> polygons, ref List <Point> outPoints, ref List <Line> outLines, ref List <Polygon> outPolygons)
        {
            B = new Point(((points[0].X + points[1].X + points[2].X) / 3), ((points[0].Y + points[1].Y + points[2].Y) / 3));

            Point NB = new Point(B.X + 5, B.Y);

            Base_Line = new Line(B, NB);


            /*
             * // step 1 :: find minimum point in Y Axis
             * minimumY = points[0]; ; // any intial value
             * for (int i = 0; i < points.Count(); i++)
             * {
             *  if (points[i].Y < minimumY.Y)
             *  {
             *      minimumY = points[i];
             *      index_of_mini_Y = i;
             *  }
             *
             *  else if (points[i].Y == minimumY.Y)
             *  {
             *      if (points[i].X < minimumY.X)
             *      {
             *          minimumY = points[i];
             *          index_of_mini_Y = i;
             *      }
             *  }
             * }
             *
             * // Get Base_line
             * Base_Line.Start = minimumY;
             * Point End = new Point(minimumY.X + 5, minimumY.Y);
             * Base_Line.End = End;
             *
             *
             */

            // Comparison<Point> comp = new Comparison<Point>(compare_angle);
            OrderedSet <Point> CH = new OrderedSet <Point>(compare_angle);


            // CH.add(Points[0], Points[1], Points[2]);
            CH.Add(points[0]);
            CH.Add(points[1]);
            CH.Add(points[2]);

            Point p = points[0];                       // any intial value
            Point p_Prev, p_next;
            Line  l1 = new Line(points[0], points[1]); // any intial value

            for (int i = 3; i < points.Count(); i++)
            {
                p = points[i];
                //KeyValuePair<Point, Point> prevANDnext = CH.DirectRightAndLeftRotational(p);
                p_Prev = CH.DirectRightAndLeftRotational(p).Value;
                p_next = CH.DirectRightAndLeftRotational(p).Key;


                l1.Start = p_Prev;
                l1.End   = p_next;
                if (HelperMethods.CheckTurn(l1, p) == Enums.TurnType.Right) // Outside the polygon
                {
                    //KeyValuePair<Point, Point> prevANDnext_2 = CH.DirectRightAndLeftRotational(p_Prev);
                    Point New_pre = CH.DirectRightAndLeftRotational(p_Prev).Value;


                    l1.Start = p;
                    l1.End   = p_Prev;
                    while (HelperMethods.CheckTurn(l1, New_pre) == Enums.TurnType.Left)
                    {
                        CH.Remove(p_Prev);
                        //left support part
                        p_Prev  = New_pre;
                        New_pre = CH.DirectRightAndLeftRotational(p_Prev).Value;

                        l1.Start = p;
                        l1.End   = p_Prev;
                    } // end of while Left   Supporting Line

                    Point New_next = CH.DirectRightAndLeftRotational(p_next).Key;

                    l1.Start = p;
                    l1.End   = p_next;
                    while (HelperMethods.CheckTurn(l1, New_next) == Enums.TurnType.Right)
                    {
                        CH.Remove(p_next);
                        p_next   = New_next;
                        New_next = CH.DirectRightAndLeftRotational(p_next).Key;


                        l1.Start = p;
                        l1.End   = p_next;
                    } // // end of while Right  Supporting Line
                    // leave Pre and Next but delete the points between them
                    CH.Add(p);
                } // end of ( if condtion :: --->> point outside the triangle
            }     // end of for loop
            outPoints = CH.ToList();
        }
Beispiel #44
0
 public List<CategoryInfo> GetCategoryList(bool isWeb)
 {
     try
     {
         CategoryManager mgr = new CategoryManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.GetCategoryList();
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #45
0
        public override void Run(List <Point> points, List <Line> lines, List <Polygon> polygons, ref List <Point> outPoints, ref List <Line> outLines, ref List <Polygon> outPolygons)
        {
            List <Point> points2 = new List <Point>();

            foreach (var item in points)
            {
                if (!points2.Contains(item))
                {
                    points2.Add(item);
                }
            }
            points = points2;


            if (points.Count == 1 || points.Count == 2)
            {
                outPoints = points;
                return;
            }



            for (int i = 0; i < points.Count; i++)
            {
                bool found = false;
                for (int j = 0; j < points.Count; j++)
                {
                    for (int k = 0; k < points.Count; k++)
                    {
                        for (int z = 0; z < points.Count; z++)
                        {
                            if (points[i] != points[j] && points[i] != points[k] && points[i] != points[z])
                            {
                                Enums.PointInPolygon e = HelperMethods.PointInTriangle(points[i], points[j], points[k], points[z]);
                                if (e == Enums.PointInPolygon.Inside || e == Enums.PointInPolygon.OnEdge)
                                {
                                    points.Remove(points[i]);
                                    i--;
                                    found = true;
                                    break;
                                }
                            }
                            if (found)
                            {
                                break;
                            }
                        }
                        if (found)
                        {
                            break;
                        }
                    }
                    if (found)
                    {
                        break;
                    }
                }
            }

            outPoints = points;
        }
Beispiel #46
0
 public List<CommentInfo> GetComments(long postId, int pageId, int pageSize, bool isWeb)
 {
     try
     {
         CommentManager mgr = new CommentManager();
         HelperMethods helperMgr = new HelperMethods();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         PostInfo post = new PostManager().GetPostById(tokenInfo.Idf, 0, tokenInfo.FolderPath, postId);
         if (post.isDone == true)
             return mgr.GetComments(tokenInfo.Idf, postId, pageId, helperMgr.SetPageSize(pageSize, isWeb));
         else
             return mgr.GetOwnComments(tokenInfo.Idf, postId, pageId, helperMgr.SetPageSize(pageSize, isWeb));
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #47
0
 public bool DeletePost(long postId, bool isWeb)
 {
     try
     {
         PostManager mgr = new PostManager();
         HelperMethods helperMgr = new HelperMethods();
         TokenInfo tokenInfo = helperMgr.GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.DeletePost(tokenInfo.Idf, postId);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
        //This method is used to List out all the Person details if Id passed as 0 or no Paramater passed.
        //If its passed >0 then it will return the Singlt Person
        public ResponseResult PersonListDetail(int PID = 0)
        {
            ResponseResult r = new ResponseResult();

            try
            {
                List <CompletePerson> cp = new List <CompletePerson>();
                Person p = new Person();
                if (PID == 0)
                {
                    var pds = this.context.GetList();
                    foreach (PersonData item in pds)
                    {
                        //Converts the XML String to .Net objects
                        p = HelperMethods.XMLStringToObject <Person>(item.PersonXML);
                        cp.Add(new CompletePerson
                        {
                            PID         = item.PID,
                            PersomXML   = p,
                            CreatedDate = item.CreatedDate.ToString("MM/dd/yyyy"),
                            UpdatedDate = item.UpdatedDate?.ToString("MM/dd/yyyy")
                        });
                    }

                    if (cp.Count == 0)
                    {
                        r.ReturnResult = cp;
                        r.Message      = "No record found";
                        r.status       = ResponseStatus.Fail;
                    }
                    else
                    {
                        r.ReturnResult = cp;
                        r.Message      = "Retrived successfully.";
                        r.status       = ResponseStatus.Success;
                    }
                }
                else
                {
                    CompletePerson c  = null;
                    var            pd = context.GetList().SingleOrDefault <PersonData>(req => req.PID == PID);
                    if (pd != null)
                    {
                        //Converts the XML String to .Net objects
                        p = HelperMethods.XMLStringToObject <Person>(pd.PersonXML);
                        c = new CompletePerson
                        {
                            PID         = pd.PID,
                            PersomXML   = p,
                            CreatedDate = pd.CreatedDate.ToString("MM/dd/yyyy"),
                            UpdatedDate = pd.UpdatedDate?.ToString("MM/dd/yyyy")
                        };
                    }

                    if (c == null)
                    {
                        r.ReturnResult = c;
                        r.Message      = "No record found";
                        r.status       = ResponseStatus.Fail;
                        LogFactory.Log(LogType.Error, LogMode.TextFile, "No record found.");
                    }
                    else
                    {
                        r.ReturnResult = c;
                        r.Message      = "Retrived successfully.";
                        r.status       = ResponseStatus.Success;
                    }
                }
            }
            catch (Exception ex)
            {
                r.ReturnResult = null;
                r.Message      = "Bad Request / Internal Server error.";
                r.status       = ResponseStatus.Error;

                LogFactory.Log(LogType.Error, LogMode.TextFile, $"{ex.Message} \r\n {new StackTrace(ex, true).GetFrame(0).GetFileLineNumber()}");
            }
            return(r);
        }
Beispiel #49
0
 public List<PostInfo> GetContactPostsList(string contactToken, int pageId, int pageSize, bool isWeb)
 {
     try
     {
         PostManager mgr = new PostManager();
         HelperMethods helperMgr = new HelperMethods();
         TokenInfo tokenInfo = helperMgr.GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.GetContactPostsList(tokenInfo.Idf, JsonWebToken.DecodeToken<TokenInfo>(contactToken, CodeHelper.SecretAccessKey, true, false).Idf, tokenInfo.TerritoryId, tokenInfo.FolderPath, pageId, helperMgr.SetPageSize(pageSize, isWeb));
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #50
0
 public async void Dispose()
 {
     if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
     {
         this.inputPane.Showing        -= InputPane_Showing;
         this.inputPane.Hiding         -= InputPane_Hiding;
         this.inputPane                 = null;
         richTextBox.GotFocus          -= RichTextBox_GotFocus;
         richTextBox.Tapped            -= RichTextBox_Tapped;
         richTextBox.ZoomFactorChanged -= RichTextBox_ZoomFactorChanged;
         ribbon.RibbonTabPanelOpened   -= Ribbon_RibbonTabPanelOpened;
         ribbon.RibbonTabPanelClosed   -= Ribbon_RibbonTabPanelClosed;
     }
     ribbon.BackStageOpened -= Ribbon_BackStageOpened;
     ribbon.BackStageClosed -= Ribbon_BackStageClosed;
     this.Unloaded          -= DocumentEditor_Unloaded;
     this.Loaded            -= DocumentEditor_Loaded;
     if (highlightcolorpicker != null)
     {
         this.highlightcolorpicker.HighlightColorGridView.SelectionChanged -= HighlightColorGridView_SelectionChanged;
         this.highlightcolorpicker.HighlightColorGridView.SetBinding(GridView.SelectedIndexProperty, new Binding());
     }
     this.highlightcolorpicker = null;
     //Handled to cancel the asynchronous load operation.
     if (loadAsync != null && !loadAsync.IsCompleted && !loadAsync.IsFaulted && cancellationTokenSource != null)
     {
         cancellationTokenSource.Cancel();
         try
         {
             await loadAsync;
         }
         catch
         { }
     }
     this.richTextBox.PrintCompleted   -= RichTextBoxAdv_PrintCompleted;
     this.richTextBox.RequestNavigate  -= RichTextBoxAdv_RequestNavigate;
     this.richTextBox.SelectionChanged -= RichTextBox_SelectionChanged;
     this.richTextBox.ContentChanged   -= RichTextBox_ContentChanged;
     //Disposes the SfRichTextBoxAdv contents explicitly.
     this.richTextBox.Dispose();
     printDocumentSource = null;
     this.richTextBox    = null;
     //Un hook backstage events
     if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
     {
         if (newBackStageTabItem != null)
         {
             //Clears the backstage tab item buttons.
             newDocument.Click -= BlankDocumentButton_Click;
             HelperMethods.DisposeButton(newDocument);
             newDocument      = null;
             takeATour.Click -= TakeATourButton_Click;
             HelperMethods.DisposeButton(takeATour);
             takeATour     = null;
             letter.Click -= LetterTemplateButton_Click;
             HelperMethods.DisposeButton(letter);
             letter       = null;
             title.Click -= TitleTemplateButton_Click;
             HelperMethods.DisposeButton(title);
             title      = null;
             fax.Click -= FaxTemplateButton_Click;
             HelperMethods.DisposeButton(fax);
             fax             = null;
             toDoList.Click -= ToDoListTemplateButton_Click;
             HelperMethods.DisposeButton(toDoList);
             toDoList = null;
         }
     }
     printBackStageButton.Click -= PrintDocument_OnClick;
     printBackStageButton.Dispose();
     openBackStageButton.Click -= WordImport_Click;
     openBackStageButton.Dispose();
     openBackStageButton          = null;
     saveAsBackStageButton.Click -= WordExport_Click;
     saveAsBackStageButton.Dispose();
     saveAsBackStageButton       = null;
     helpBackaStageButton.Click -= HelpButton_Clicked;
     helpBackaStageButton.Dispose();
     helpBackaStageButton       = null;
     exitBackStageButton.Click -= ExitButton_Click;
     exitBackStageButton.Dispose();
     exitBackStageButton = null;
     //Disposing the BackStage
     this.ribbon.BackStage.Dispose();
     //Disposing the QAT
     this.ribbon.QuickAccessToolBar.Dispose();
     //Disposing the Ribbon.
     this.ribbon.Dispose();
     //Disposing the RibbonPage
     if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
     {
         this.ribbonPage.Dispose();
     }
     mainGrid.Resources.Clear();
     mainGrid.Resources = null;
     this.Resources.Clear();
     this.Resources = null;
     busy.ClearValue(ProgressBar.IsIndeterminateProperty);
     busy.ClearValue(ProgressBar.ForegroundProperty);
     busy.ClearValue(ProgressBar.VerticalAlignmentProperty);
     UnlinkChildrens(this);
     UnlinkChildrens(this.ribbon.BackStage);
 }
Beispiel #51
0
 public List<NotificationInfo> GetNotificationByUser(int pageId, int pageSize, bool isWeb)
 {
     try
     {
         PostManager mgr = new PostManager();
         HelperMethods helperMgr = new HelperMethods();
         var userIdf = helperMgr.GetUserIdf(isWeb, HttpContext.Current);
         return mgr.GetNotificationByUser(userIdf, pageId, helperMgr.SetPageSize(pageSize, isWeb));
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #52
0
        public override void VisitAssignmentStatement(AssignmentStatement assignment)
        {
            if (assignment == null)
            {
                return;
            }

            Construct cons = assignment.Source as Construct;

            if (cons == null)
            {
                goto JustVisit;
            }

            if (!(cons.Type.IsDelegateType()))
            {
                goto JustVisit;
            }

            UnaryExpression ue = cons.Operands[1] as UnaryExpression;

            if (ue == null)
            {
                goto JustVisit;
            }

            MemberBinding mb = ue.Operand as MemberBinding;

            if (mb == null)
            {
                goto JustVisit;
            }

            Method m = mb.BoundMember as Method;

            if (m.IsStatic)
            {
                mb = assignment.Target as MemberBinding;
                if (mb == null)
                {
                    goto JustVisit;
                }

                if (mb.TargetObject != null)
                {
                    goto JustVisit;
                }

                // Record the static cache field used to hold the static closure
                MembersToDuplicate.Add(mb.BoundMember);

                goto End;
            }

JustVisit:
            if (assignment.Source == null)
            {
                goto JustVisit2;
            }

            if (assignment.Source.NodeType != NodeType.Pop)
            {
                goto JustVisit2;
            }

            mb = assignment.Target as MemberBinding;

            if (mb == null)
            {
                goto JustVisit2;
            }

            if (mb.TargetObject != null)
            {
                goto JustVisit2;
            }

            if (mb.BoundMember == null)
            {
                goto JustVisit2;
            }

            if (HelperMethods.Unspecialize(mb.BoundMember.DeclaringType) != this.containingType)
            {
                goto JustVisit2;
            }

            MembersToDuplicate.Add(mb.BoundMember);

JustVisit2:
            ;

End:
            base.VisitAssignmentStatement(assignment);
        }
Beispiel #53
0
 public bool Vote(long postId, bool voteOption, bool isWeb)
 {
     try
     {
         PostManager mgr = new PostManager();
         TokenInfo tokenInfo = new HelperMethods().GetUserToken<TokenInfo>(isWeb, HttpContext.Current);
         return mgr.Vote(postId, tokenInfo.Idf, voteOption, tokenInfo.TerritoryId);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }
Beispiel #54
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="containingType">Type containing the method containing the closures</param>
 public FindClosurePartsToDuplicate(TypeNode containingType, Method sourceMethod)
 {
     this.CurrentMethod  = HelperMethods.Unspecialize(sourceMethod);
     this.containingType = HelperMethods.Unspecialize(containingType);
 }
Beispiel #55
0
        public ActionResult <GenericResponseModel> Update([FromBody] AssetDto pObject)
        {
            var loUserId          = HelperMethods.GetApiUserIdFromToken(HttpContext.User.Identity);
            var loGenericResponse = new GenericResponseModel
            {
                Status = "Fail",
                Code   = -1
            };

            var loData = GetData.GetAssetById(pObject.row_guid.ToString());

            if (loData == null)
            {
                loGenericResponse.Status  = "Fail";
                loGenericResponse.Code    = -1;
                loGenericResponse.Message = "Gayrimenkul bulunamadı!";
                return(loGenericResponse);
            }

            //if (pObject.first_announcement_date == null)
            //{
            //    if (DateTime.TryParse(pObject.first_announcement_date_str, out var loFirstAnnonce))
            //        pObject.first_announcement_date = loFirstAnnonce;
            //    else
            //    {
            //        loGenericResponse.Status = "Fail";
            //        loGenericResponse.Code = -1;
            //        loGenericResponse.Message = "İlan yayın başlangıç tarihi girilmeden işleme devam edilemez.";
            //        return loGenericResponse;
            //    }

            //    if ((loData.row_create_date.Value - pObject.first_announcement_date.Value).TotalMinutes > 2)
            //    {
            //        loGenericResponse.Status = "Fail";
            //        loGenericResponse.Code = -1;
            //        loGenericResponse.Message = "Geçmiş tarihili ilan başlatılamaz.";
            //        return loGenericResponse;
            //    }
            //}

            if (pObject.last_announcement_date == null)
            {
                if (DateTime.TryParse(pObject.last_announcement_date_str, out var loLastAnnonce))
                {
                    loData.last_announcement_date = loLastAnnonce;
                    if (loData.last_announcement_date < loData.first_announcement_date)
                    {
                        loGenericResponse.Status  = "Fail";
                        loGenericResponse.Code    = -1;
                        loGenericResponse.Message = "İlanın bitiş tarihi başlangıç tarihinden önce olamaz";
                        return(loGenericResponse);
                    }
                }
            }

            if (pObject.last_offer_date == null)
            {
                if (DateTime.TryParse(pObject.last_offer_date_str, out var loOffer))
                {
                    loData.last_offer_date = loOffer;
                    if (loData.last_offer_date < loData.last_announcement_date)
                    {
                        loGenericResponse.Status  = "Fail";
                        loGenericResponse.Code    = -1;
                        loGenericResponse.Message = "Son teklif tarihi, ilan bitiş tarihinden önce olamaz";
                        return(loGenericResponse);
                    }
                }
            }

            loData.is_deleted  = pObject.is_deleted ?? loData.is_deleted;
            loData.is_active   = pObject.is_active ?? loData.is_active;
            loData.asset_no    = pObject.asset_no ?? loData.asset_no;
            loData.city_id     = pObject.city_id ?? loData.city_id;
            loData.city        = pObject.city ?? loData.city;
            loData.district_id = pObject.district_id ?? loData.district_id;
            loData.district    = pObject.district ?? loData.district;
            loData.category_type_system_type_id = pObject.category_type_system_type_id ?? loData.category_type_system_type_id;
            loData.asset_type_system_type_id    = pObject.asset_type_system_type_id ?? loData.asset_type_system_type_id;
            loData.size                     = pObject.size ?? loData.size;
            loData.block_number             = pObject.block_number ?? loData.block_number;
            loData.plot_number              = pObject.plot_number ?? loData.plot_number;
            loData.share                    = pObject.share ?? loData.share;
            loData.explanation              = pObject.explanation ?? loData.explanation;
            loData.starting_amount          = pObject.starting_amount ?? loData.starting_amount;
            loData.registry_price           = pObject.registry_price ?? loData.registry_price;
            loData.max_offer_amount         = pObject.max_offer_amount ?? loData.max_offer_amount;
            loData.minimum_increate_amout   = pObject.minimum_increate_amout ?? loData.minimum_increate_amout;
            loData.guarantee_amount         = pObject.guarantee_amount ?? loData.guarantee_amount;
            loData.is_compatible_for_credit = pObject.is_compatible_for_credit ?? loData.is_compatible_for_credit;
            loData.thumb_path               = pObject.thumb_path ?? loData.thumb_path;
            loData.agreement_guid           = pObject.agreement_guid ?? loData.agreement_guid;
            loData.is_sold                  = pObject.is_sold ?? loData.is_sold;
            loData.free_text_no             = pObject.free_text_no ?? loData.free_text_no;
            loData.show_last_offer_date     = pObject.show_last_offer_date ?? loData.show_last_offer_date;
            //ilan başlangıç tarihi değiştirilemez loData.first_announcement_date = pObject.first_announcement_date ?? loData.first_announcement_date;
            loData.asset_name      = pObject.asset_name ?? loData.asset_name;
            loData.bank_guid       = pObject.bank_guid ?? loData.bank_guid;
            loData.row_update_date = DateTime.Now;
            loData.row_update_user = loUserId;
            loData.city            = loData.city.ToUpper();
            loData.district        = loData.district?.ToUpper();
            loData.address         = loData.address?.ToUpper();
            loData.share           = loData.share?.ToUpper();
            loData.asset_name      = loData.asset_name?.ToUpper();
            loData.asset_no        = loData.asset_no?.ToUpper();

            if (loData.registry_price == null)
            {
                loData.registry_price = 0;
            }

            if (loData.free_text_no == null)
            {
                loData.free_text_no = "";
            }

            if (pObject.asset_photos != null && pObject.asset_photos.Any())
            {
                loData.asset_photos = pObject.asset_photos;
            }


            var loResult = Crud <Asset> .UpdateAsset(loData);

            if (loResult)
            {
                loGenericResponse.Data   = pObject;
                loGenericResponse.Status = "Ok";
                loGenericResponse.Code   = 200;
            }
            else
            {
                loGenericResponse.Status  = "Fail";
                loGenericResponse.Code    = -1;
                loGenericResponse.Message = "Gayrimenkul kaydı başarısız";
            }

            return(loGenericResponse);
        }
Beispiel #56
0
 public bool DeleteComment(long postId, CommentInfo info, bool isWeb)
 {
     try
     {
         CommentManager mgr = new CommentManager();
         Guid userIdf = new HelperMethods().GetUserIdf(isWeb, HttpContext.Current);
         info.PostId = postId;
         info.UserIdf = userIdf;
         return mgr.DeleteComment(info);
     }
     catch (Exception ex)
     {
         throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
 }