예제 #1
0
        protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List <Microsoft.SharePoint.WebControls.PickerEntity> resolved)
        {
            if (!entityTypes.Contains(SPClaimEntityTypes.Trusted))
            {
                return;
            }

            var organizationMatches = SearchOrganizations(resolveInput);

            if (organizationMatches.Count() > 0)
            {
                foreach (var match in organizationMatches)
                {
                    PickerEntity pe = GetPickerEntity(match, OrganizationClaimType, filters[OrganizationKey]);
                    resolved.Add(pe);
                }
            }

            var roleMatches = SearchRoles(resolveInput);

            if (roleMatches.Count() > 0)
            {
                foreach (var match in roleMatches)
                {
                    PickerEntity pe = GetPickerEntity(match, Microsoft.IdentityModel.Claims.ClaimTypes.Role, filters[RoleKey]);
                    resolved.Add(pe);
                }
            }
        }
예제 #2
0
        /// <summary>
        ///     Get selecte user information from people editor control
        /// </summary>
        /// <param name="people"></param>
        /// <param name="currentWeb"></param>
        /// <returns></returns>
        public SPFieldUserValue GetSingleUserFromPeopleEditor(PeopleEditor people, SPWeb currentWeb)
        {
            SPFieldUserValue userValue = null;

            try
            {
                if (people.ResolvedEntities.Count <= 1)
                {
                    PickerEntity user = (PickerEntity)people.ResolvedEntities[0];

                    switch ((string)user.EntityData["PrincipalType"])
                    {
                    case "User":
                        SPUser webUser = currentWeb.EnsureUser(user.Key);
                        userValue = new SPFieldUserValue(currentWeb, webUser.ID, webUser.Name);
                        break;

                    case "SharePointGroup":
                        SPGroup siteGroup = currentWeb.SiteGroups[user.EntityData["AccountName"].ToString()];
                        userValue = new SPFieldUserValue(currentWeb, siteGroup.ID, siteGroup.Name);
                        break;
                    }
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at GetSingleUserFromPeopleEditor function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }
            return(userValue);
        }
예제 #3
0
        private PickerEntity GetEntity(SPListItem item)
        {
            LookupFieldWithPickerPropertyBag propertyBag = new LookupFieldWithPickerPropertyBag(this.CustomProperty);

            PickerEntity entity       = new PickerEntity();
            string       displayValue = null;

            try
            {
                displayValue = item[propertyBag.FieldId] as String;
            }
            catch
            {
                //field has been deleted
            }

            if (displayValue != null &&
                item.Fields[propertyBag.FieldId].Type == SPFieldType.Calculated &&
                item[propertyBag.FieldId] != null &&
                item[propertyBag.FieldId].ToString().Contains("#"))
            {
                entity.DisplayText = displayValue.ToString().Split('#')[1];
            }
            else
            {
                entity.DisplayText = displayValue ?? "";
            }
            entity.Key         = item.ID.ToString();
            entity.Description = entity.DisplayText;
            entity.IsResolved  = true;

            return(entity);
        }
예제 #4
0
        /// <summary>
        /// проверка значения. Обычно при щелчке на кнопке Проверить имена
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public override PickerEntity ValidateEntity(PickerEntity entity)
        {
            if (entity.IsResolved)
            {
                return(entity);
            }

            var     dm  = new DataManager(PickerData.ConnectionString, PickerData.QueryString);
            DataRow row = null;

            SPSecurity.RunWithElevatedPrivileges(() => row = dm.GetRecord(entity.DisplayText));

            if (row == null)
            {
                return(entity);
            }

            // Resolve entity
            var pe = new PickerEntity
            {
                Key         = row["ID"].ToString(),
                DisplayText = row["Value"].ToString()
            };

            entity            = pe;
            entity.IsResolved = true;

            ////пока не работает
            //if (entity.DisplayText.Contains(CustomExternalLookupValue.Separator))
            //    ErrorMessage = string.Format("Предупреждение: значение содержит недопустимые для данного компонента символы {0} и будет сохранено изменённым. Попробуйте изменить значение во внешнем источнике данных", CustomExternalLookupValue.Separator);

            return(entity);
        }
예제 #5
0
        protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List <Microsoft.SharePoint.WebControls.PickerEntity> resolved)
        {
            UPSClaimProviderLogger.LogDebug("FillResolve type1 invoked!");
            string outputString;

            outputString = $"resolveInput: {resolveInput}";
            UPSClaimProviderLogger.LogDebug(outputString);

            List <User> foundUsers = usersDAL.GetUsersBySearchPattern(resolveInput);

            if (foundUsers.Count > 0)
            {
                UPSClaimProviderLogger.LogDebug($"Count of users found: {foundUsers.Count} - input resolved");
                foundUsers.ForEach((foundUser) =>
                {
                    PickerEntity entity = GetPickerEntity(foundUser);
                    resolved.Add(entity);
                    UPSClaimProviderLogger.LogDebug($"Added PickerEntity to resolved with Claim -  Claim.Value: {entity.Claim.Value}, Claim.ClaimType: {entity.Claim.ClaimType}, Claim.OriginalIssuer: {entity.Claim.OriginalIssuer}");
                });
            }
            else if (foundUsers.Count == 0)
            {
                UPSClaimProviderLogger.LogDebug("No users found - input unresolved");
            }
            ;
        }
예제 #6
0
        protected void DdlReportingToSelectedIndexChanged(object sender, EventArgs e)
        {
            using (var site = new SPSite(SPContext.Current.Site.Url))
            {
                using (var web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    var empid = System.Web.HttpContext.Current.Request.QueryString["EmpId"];

                    var emplist = web.Lists.TryGetList("Employee Screen");
                    var empitem = emplist.GetItemById(Convert.ToInt16(empid));
                    empSPid.Value = empid;
                    var entity = new PickerEntity
                    {
                        DisplayText =
                            new SPFieldUserValue(web, empitem["Employee Name"].ToString()).User
                            .
                            LoginName
                    };
                    txtempusername.Text = web.AllUsers[entity.DisplayText].Name;
                    var leavelist      = SPContext.Current.Web.Lists.TryGetList(Utilities.LeaveRequest);
                    var leavelistitems = GetListItemCollection(leavelist, "RequestedFrom", txtempusername.Text, "Status", "Pending");

                    if (leavelistitems != null && leavelistitems.Count > 0)
                    {
                        LblError.Text       = "Make sure that no pending leave requests for previous manager";
                        BtnRegister.Enabled = false;
                    }
                    else
                    {
                        BtnRegister.Enabled = true;
                    }
                }
            }
        }
예제 #7
0
        public PickerEntity GetEntityById(int id)
        {
            PickerEntity entity = null;

            if (id > 0)
            {
                LookupFieldWithPickerPropertyBag propertyBag = new LookupFieldWithPickerPropertyBag(this.CustomProperty);

                using (SPWeb web = SPContext.Current.Site.OpenWeb(propertyBag.WebId))
                {
                    SPList  list      = web.Lists[propertyBag.ListId];
                    SPQuery queryById = new SPQuery();
                    queryById.ViewAttributes = "Scope=\"Recursive\"";
                    queryById.Query          =
                        string.Format(
                            "<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">{0}</Value></Eq></Where>", id);
                    SPListItemCollection items = list.GetItems(queryById);
                    if (items.Count > 0)
                    {
                        entity = this.GetEntity(items[0]);
                    }
                }
            }

            return(entity);
        }
예제 #8
0
        public override PickerEntity ValidateEntity(PickerEntity needsValidation)
        {
            PickerEntity entity = needsValidation;

            if (!string.IsNullOrEmpty(needsValidation.DisplayText))
            {
                using (SPWeb web = SPControl.GetContextWeb(Context))
                {
                    FieldLookupWithPickerPropertyBag propertyBag = new FieldLookupWithPickerPropertyBag(this.CustomProperty);

                    SPList  list      = web.Lists[propertyBag.ListId];
                    SPQuery queryById = new SPQuery();
                    queryById.Query = string.Format("<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">{0}</Value></Eq></Where>", needsValidation.Key);
                    SPListItemCollection items = list.GetItems(queryById);
                    if (items.Count > 0)
                    {
                        entity = this.GetEntity(items[0]);
                    }
                    else
                    {
                        SPQuery queryByTitle = new SPQuery();
                        queryByTitle.Query = string.Format("<Where><Eq><FieldRef Name=\"{0}\"/><Value Type=\"Text\">{1}</Value></Eq></Where>", propertyBag.FieldId, needsValidation.DisplayText);
                        items = list.GetItems(queryByTitle);
                        if (items.Count > 0)
                        {
                            entity = this.GetEntity(items[0]);
                        }
                    }
                }
            }

            return(entity);
        }
예제 #9
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
            {
                return;
            }

            //get the collection of users from people editor
            string users = string.Empty;
            SPFieldUserValueCollection spFieldUserValues = new SPFieldUserValueCollection();
            int index = 0;

            for (index = 0; index <= this.peContactUsers.ResolvedEntities.Count - 1; ++index)
            {
                PickerEntity objEntity = (PickerEntity)this.peContactUsers.ResolvedEntities[index];
                users += objEntity.EntityData["AccountName"] + ",";
            }

            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_INTERNAL_EMAIL_PROPERTY, users.TrimEnd(','));
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_EXTERNAL_EMAIL_PROPERTY, txtContactEmail.Text);
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_ADD_DATE_EMAIL_PROPERTY, chkAddDate.Checked.ToString());
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_TITLE_EMAIL_PROPERTY, txtEmailTitle.Text);
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_BODY_HTML_EMAIL_PROPERTY, txtHtmlBody.Text);
            GoToListSettingsPage();
        }
예제 #10
0
        /// <summary>
        /// Required if you implement claim resolve in the People Picker.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="entityTypes"></param>
        /// <param name="resolveInput"></param>
        /// <param name="resolved"></param>
        protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List <PickerEntity> resolved)
        {
            string        keyword         = resolveInput.ToLower();
            Hashtable     knownClaims     = CRMUserInfo.GetAllClaims();
            List <string> knownClaimsList = new List <string>();

            //Convert the knownClaims.Key into a List<string> for LINQ query.
            foreach (string claim in knownClaims.Keys)
            {
                knownClaimsList.Add(claim);
            }

            var claimQuery = knownClaimsList.Where(claim => claim.IndexOf(keyword) >= 0).Select(claim => claim);

            foreach (string claimValue in claimQuery)
            {
                //Get the ClaimType for the claim type.
                //For example, if you are search "SalesManager", the ClaimType will be CRMClaimType.Role.

                string claimType = CRMUserInfo.GetClaimTypeForRole((string)knownClaims[claimValue]);

                PickerEntity entity = CreatePickerEntity();
                entity.Claim       = CreateClaim(claimType, claimValue, Microsoft.IdentityModel.Claims.ClaimValueTypes.String);
                entity.Description = claimValue;
                entity.DisplayText = claimValue;
                entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = claimValue;
                entity.EntityType = SPClaimEntityTypes.FormsRole;
                entity.IsResolved = true;
                resolved.Add(entity);
            }
        }
예제 #11
0
        private PickerEntity GetPickerEntity(User user)
        {
            UPSClaimProviderLogger.LogDebug("GetPickerEntity invoked!");

            PickerEntity entity = CreatePickerEntity();

            string originalIssuer = SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, SPTrustedIdentityTokenIssuerName);

            UPSClaimProviderLogger.LogDebug($"originalIssuer: {originalIssuer}");
            entity.Claim = new SPClaim(UPSEmailAddressClaimType, user.Email, UPSEmailAddressClaimValueType, originalIssuer);
            string claimAsString = entity.Claim.ToEncodedString();

            UPSClaimProviderLogger.LogDebug($"claimAsString: {claimAsString}");


            entity.Description = user.Username;
            entity.DisplayText = user.Username;
            entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = user.Username;
            entity.EntityData[PeopleEditorEntityDataKeys.Email]       = user.Email;
            entity.EntityData[PeopleEditorEntityDataKeys.AccountName] = user.Email;
            entity.EntityData[PeopleEditorEntityDataKeys.Department]  = user.Department;
            entity.EntityData[PeopleEditorEntityDataKeys.JobTitle]    = user.JobTitle;
            entity.EntityType = SPClaimEntityTypes.User;
            entity.IsResolved = true;
            return(entity);
        }
        /// <summary>
        /// �������� ��������. ������ ��� ������ �� ������ ��������� �����
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public override PickerEntity ValidateEntity(PickerEntity entity)
        {
            if (entity.IsResolved)
                return entity;

            var dm = new DataManager(PickerData.ConnectionString, PickerData.QueryString);
            DataRow row = null;
            SPSecurity.RunWithElevatedPrivileges(() => row = dm.GetRecord(entity.DisplayText));

            if (row == null)
                return entity;

            // Resolve entity
            var pe = new PickerEntity
                         {
                             Key = row["ID"].ToString(),
                             DisplayText = row["Value"].ToString()
                         };
            entity = pe;
            entity.IsResolved = true;

            ////���� �� ��������
            //if (entity.DisplayText.Contains(CustomExternalLookupValue.Separator))
            //    ErrorMessage = string.Format("��������������: �������� �������� ������������ ��� ������� ���������� ������� {0} � ����� ��������� ���������. ���������� �������� �������� �� ������� ��������� ������", CustomExternalLookupValue.Separator);

            return entity;
        }
예제 #13
0
        //获取控件中的值
        private SPFieldUserValue GetUserValue(SPWeb web, PickerEntity picker)
        {
            SPUser           user       = web.EnsureUser(picker.Key);
            SPFieldUserValue fieldvalue = new SPFieldUserValue(web, user.ID, user.LoginName);

            return(fieldvalue);
        }
예제 #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                UCore.Administration admin = new Core.Administration();
                var settings = admin.GetSettings();
                if (settings != null)
                {
                    txtMailTo.Text = settings.MailTo;
                    var visibleToUsers = settings.VisibleTo?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                                         ?? new string[0];
                    foreach (var user in visibleToUsers)
                    {
                        var usersplit = user.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
                        if (usersplit.Length == 2)
                        {
                            PickerEntity entity = new PickerEntity();
                            entity.IsResolved  = false;
                            entity.DisplayText = usersplit[0];
                            entity.Key         = usersplit[1];
                            ppVisibleTo.AllEntities.Add(entity);
                        }
                    }

                    ppVisibleTo.Validate();
                }
            }
        }
예제 #15
0
        protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, Microsoft.SharePoint.WebControls.SPProviderHierarchyTree searchTree)
        {
            UPSClaimProviderLogger.LogDebug("FillSearch invoked!");

            LogDebugSearchTree(searchTree);

            string outputString;

            outputString = $"searchPattern: {searchPattern}, hierarchyNodeID: {hierarchyNodeID}, maxCount: {maxCount}";
            UPSClaimProviderLogger.LogDebug(outputString);

            List <User> foundUsers = usersDAL.GetUsersBySearchPattern(searchPattern);

            if (foundUsers.Count > 0)
            {
                UPSClaimProviderLogger.LogDebug($"Count of users found: {foundUsers.Count}");

                foundUsers.ForEach((foundUser) =>
                {
                    PickerEntity entity = GetPickerEntity(foundUser);
                    searchTree.AddEntity(entity);
                    UPSClaimProviderLogger.LogDebug($"Added PickerEntity with Claim -  Claim.Value: {entity.Claim.Value}, Claim.ClaimType: {entity.Claim.ClaimType}, Claim.OriginalIssuer: {entity.Claim.OriginalIssuer}");
                });
            }
            else if (foundUsers.Count == 0)
            {
                UPSClaimProviderLogger.LogDebug("No users found");
            }
            ;
        }
예제 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public override PickerEntity ValidateEntity(PickerEntity entity)
        {
            if (entity != null)
            {
                HTML5VideoPickerEntity videoEntity = new HTML5VideoPickerEntity(entity);
                entity = ValidateEntity(videoEntity) as PickerEntity;

                if (!entity.IsResolved)
                {
                    PickerEntity[] resolved = ResolveErrorBySearch(entity.DisplayText);
                    if (resolved != null && resolved.Count() == 1)
                    {
                        return(resolved[0]);
                        //entity.IsResolved = true;
                    }
                    else
                    {
                        entity.MultipleMatches.Add(resolved);
                    }
                    return(entity);
                }
                else
                {
                    return(entity);
                }
            }
            else
            {
                return(entity);
            }
        }
예제 #17
0
        public HTML5VideoPickerEntity(PickerEntity entity)
        {
            this.EntityData  = entity.EntityData;
            this.Key         = entity.Key;
            this.Src         = entity.Key;
            this.DisplayText = entity.DisplayText;
            try
            {
                if (entity.EntityData.ContainsKey("ItemId"))
                {
                    this.ItemId = new Guid(entity.EntityData["ItemId"].ToString());
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            try
            {
                if (entity.EntityData.ContainsKey("WebId"))
                {
                    this.WebId = new Guid(entity.EntityData["WebId"].ToString());
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            this.IsResolved = entity.IsResolved;
        }
예제 #18
0
        public void EmployeeDetails()
        {
            try
            {
                if (System.Web.HttpContext.Current.Request.QueryString["EmpId"] != null)
                {
                    using (var site = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (var web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            var empid = System.Web.HttpContext.Current.Request.QueryString["EmpId"];

                            var emplist = web.Lists.TryGetList("Employee Screen");
                            var empitem = emplist.GetItemById(Convert.ToInt16(empid));
                            empSPid.Value = empid;

                            txtempid.Text     = empitem["Title"].ToString();
                            txtfristname.Text = empitem["First Name"].ToString();
                            txtlastname.Text  = empitem["Last Name"].ToString();

                            var entity = new PickerEntity
                            {
                                DisplayText =
                                    new SPFieldUserValue(web, empitem["Employee Name"].ToString()).User.LoginName
                            };

                            txtempusername.Text      = entity.DisplayText;
                            DdlDep.SelectedItem.Text = empitem["Department"].ToString();

                            DdlDesignation.SelectedItem.Text = empitem["Designation"].ToString();
                            DdlEmptype.SelectedItem.Text     = empitem["Employee Type"].ToString();
                            hdnCurrentEmpType.Value          = empitem["Employee Type"].ToString();
                            DtDoj.SelectedDate = Convert.ToDateTime(empitem["Date of Join"].ToString());

                            if (empitem["Employee Type"].ToString().Trim() == "Permanent")
                            {
                                if (empitem["Date of Permanent"] != null)
                                {
                                    DtDOP.SelectedDate = Convert.ToDateTime(empitem["Date of Permanent"].ToString());
                                }
                                chkPrePL.Enabled = false;
                            }
                            var spv = new SPFieldLookupValue(empitem["Manager"].ToString());
                            ddlReportingTo.Items.FindByText(spv.LookupValue).Selected = true;
                            if (empitem["Status"].ToString().Trim() != "Active")
                            {
                                BtnRegister.Enabled = false;
                            }

                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LblError.Text = ex.Message;
            }
        }
        private PickerEntity GetPickerEntity(string ClaimValue)
        {
            //We have a match, create a matching entity.
            PickerEntity pe = CreatePickerEntity();

            //Set the claim associated with this match.
            pe.Claim = CreateClaim(SqlClaimType, ClaimValue, SqlClaimValueType);

            //Set the tooltip that is displayed when you hover over the resolved claim.
            pe.Description = SqlClaims.ProviderDisplayName + ":" + ClaimValue;

            //Set the text we will display.
            pe.DisplayText = ClaimValue;

            //Store it here too in the hashtable **.
            pe.EntityData[PeopleEditorEntityDataKeys.DisplayName] = ClaimValue;

            //User entity.
            pe.EntityType = SPClaimEntityTypes.FormsRole;

            //Flag the entry as being resolved.
            pe.IsResolved = true;

            //This is the first part of the description that shows
            //up above the matches, like Role: Forms Authentication when
            //you do an FBA search and find a matching role.
            pe.EntityGroupName = "Favorite Team";

            return(pe);
        }
        protected virtual PickerEntity GetPickerEntity(Auth0.User auth0User, string claimEntityType)
        {
            PickerEntity pe    = CreatePickerEntity();
            SPClaim      claim = null;

            if (claimEntityType == SPClaimEntityTypes.User)
            {
                claim = new SPClaim(
                    this.identifierClaimType,
                    string.IsNullOrEmpty(this.auth0Config.IdentifierUserField) || this.auth0Config.IdentifierUserField == "Email" ?
                    auth0User.UniqueEmail() :
                    Utils.GetPropValue(auth0User, this.auth0Config.IdentifierUserField).ToString(),
                    Microsoft.IdentityModel.Claims.ClaimValueTypes.String,
                    SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, this.associatedSPTrustedLoginProvider.Name));

                var displayText = !string.IsNullOrEmpty(auth0User.FamilyName) && !string.IsNullOrEmpty(auth0User.GivenName) ?
                                  string.Format("{0} {1}", auth0User.GivenName, auth0User.FamilyName) : auth0User.Name;

                pe.DisplayText =
                    !string.IsNullOrEmpty(displayText) ?
                    string.Format("{0} ({1})", displayText, auth0User.Email) :
                    auth0User.Email;

                pe.Description = string.Format(
                    "Email: {0}; Name: {1}",
                    auth0User.Email,
                    auth0User.Name);

                pe.EntityType = SPClaimEntityTypes.User;
                pe.EntityData[PeopleEditorEntityDataKeys.DisplayName] = displayText;
                pe.EntityData[PeopleEditorEntityDataKeys.Email]       = auth0User.Email;
                pe.EntityData["Picture"] = auth0User.Picture;
            }
            else if (claimEntityType == SPClaimEntityTypes.FormsRole)
            {
                claim = new SPClaim(
                    ConnectionClaimType,
                    auth0User.Identities.First().Connection,
                    Microsoft.IdentityModel.Claims.ClaimValueTypes.String,
                    SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, this.associatedSPTrustedLoginProvider.Name));

                pe.DisplayText = string.Format(
                    "All Users ({0})",
                    auth0User.Identities.First().Connection);

                pe.Description = string.Format(
                    "[{0}] All Users from '{1}'",
                    ProviderInternalName,
                    auth0User.Identities.First().Connection);

                pe.EntityType = SPClaimEntityTypes.FormsRole;
            }

            pe.Claim           = claim;
            pe.IsResolved      = true;
            pe.EntityGroupName = this.pickerEntityGroupName;

            return(pe);
        }
        public override PickerEntity ValidateEntity(PickerEntity needsValidation)
        {
            PickerEntity entity = needsValidation;

            if (!string.IsNullOrEmpty(needsValidation.Key))
            {
                LookupFieldWithPickerPropertyBag propertyBag = new LookupFieldWithPickerPropertyBag(this.CustomProperty);

                using (SPWeb web = SPContext.Current.Site.OpenWeb(propertyBag.WebId))
                {
                    SPList list = web.Lists[propertyBag.ListId];
                    SPField field = null;
                    string fieldType = null;

                    if (needsValidation.Key == needsValidation.DisplayText)
                    {
                        field = list.Fields[propertyBag.FieldId];
                        fieldType = field.TypeAsString;
                    }
                    else
                    {
                        field = list.Fields[SPBuiltInFieldId.ID];
                        fieldType = field.TypeAsString;
                    }

                    string valueType = field.TypeAsString;
                    if (field.Type == SPFieldType.Calculated)
                    {
                        valueType = "Text";
                    }

                    string queryString = String.Empty;
                    if (string.IsNullOrEmpty(propertyBag.FilterQuery))
                    {

                        queryString = string.Format(
                        "<Where><Eq><FieldRef Name=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Eq></Where>",
                        field.InternalName, valueType, needsValidation.Key, propertyBag.FilterQuery);
                    }
                    else
                    {
                        queryString = string.Format(
                       "<Where><And><Eq><FieldRef Name=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Eq>{3}</And></Where>",
                       field.InternalName, valueType, needsValidation.Key, propertyBag.FilterQuery);
                    }
                    SPQuery queryByTitle = new SPQuery();
                    queryByTitle.Query = queryString;
                    queryByTitle.ViewAttributes = "Scope=\"Recursive\"";
                    SPListItemCollection items = list.GetItems(queryByTitle);
                    if (items.Count == 1)
                    {
                        entity = this.GetEntity(items[0]);
                    }

                }
            }

            return entity;
        }
 public static PickerEntity CreatePickerEntity(int id, string value)
 {
     var pe = new PickerEntity
                  {
                      Key = id.ToString(),
                      DisplayText = value
                  };
     return pe;
 }
        //protected override PickerEntity[] ResolveErrorBySearch(string unresolvedText)
        //{
        //    List<PickerEntity> entities = new List<PickerEntity>();

        //    if (propBag == null)
        //    {
        //        propBag = new GenericEntityPickerPropertyBag(this.CustomProperty);
        //    }

        //    using (SPWeb web = SPContext.Current.Site.OpenWeb(propBag.LookupWebID))
        //    {
        //        SPList list = web.Lists[propBag.LookupListID];
        //        SPField field = list.Fields[propBag.LookupFieldInternalName];
        //        string valueType = field.TypeAsString;

        //        if (field.Type == SPFieldType.Calculated)
        //        {
        //            valueType = "Text";
        //        }

        //        SPQuery query = new SPQuery();
        //        query.ViewAttributes = "Scope=\"Recursive\"";
        //        query.Query =
        //            string.Format(
        //                "<Where><Contains><FieldRef Name=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Contains></Where>",
        //                field.InternalName, valueType, unresolvedText);
        //        SPListItemCollection items = list.GetItems(query);

        //        foreach (SPListItem item in items)
        //        {
        //            entities.Add(this.GetEntity(item));
        //        }
        //    }

        //    return entities.ToArray();
        //}

        public override PickerEntity ValidateEntity(PickerEntity needsValidation)
        {
            PickerEntity entity = needsValidation;

            if (propBag == null)
            {
                propBag = new GenericEntityPickerPropertyBag(this.CustomProperty);
            }

            if (!string.IsNullOrEmpty(needsValidation.Key))
            {
                try
                {
                    using (SPWeb web = SPContext.Current.Site.OpenWeb(propBag.LookupWebID))
                    {
                        SPList  list      = web.Lists[propBag.LookupListID];
                        SPField field     = null;
                        string  fieldType = null;

                        if (needsValidation.Key == needsValidation.DisplayText)
                        {
                            field     = list.Fields.GetFieldByInternalName(propBag.LookupFieldInternalName);
                            fieldType = field.TypeAsString;
                        }
                        else
                        {
                            field     = list.Fields[SPBuiltInFieldId.ID];
                            fieldType = field.TypeAsString;
                        }

                        string valueType = field.TypeAsString;
                        if (field.Type == SPFieldType.Calculated)
                        {
                            valueType = "Text";
                        }

                        string queryString = String.Empty;

                        queryString = string.Format(
                            "<Where><Eq><FieldRef Name=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Eq></Where>",
                            field.InternalName, valueType, needsValidation.Key);

                        SPQuery queryByTitle = new SPQuery();
                        queryByTitle.Query          = queryString;
                        queryByTitle.ViewAttributes = "Scope=\"Recursive\"";
                        SPListItemCollection items = list.GetItems(queryByTitle);
                        if (items.Count == 1)
                        {
                            entity = this.GetEntity(items[0]);
                        }
                    }
                }
                catch { }
            }

            return(entity);
        }
        protected override void GetControlValue()
        {
            ArrayList resolvedEntities = _control.ResolvedEntities;

            if (resolvedEntities.Count == 1)
            {
                PickerEntity entity = (PickerEntity)resolvedEntities[0];
                Value = entity.Key;
            }
        }
        protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List <Microsoft.SharePoint.WebControls.PickerEntity> resolved)
        {
            DBUser user = DBHelper.FindExact(resolveInput);

            if (null != user)
            {
                PickerEntity entity = GetPickerEntity(user);
                resolved.Add(entity);
            }
        }
        protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, Microsoft.SharePoint.WebControls.SPProviderHierarchyTree searchTree)
        {
            List <DBUser> users = DBHelper.Search(searchPattern);

            foreach (var user in users)
            {
                PickerEntity entity = GetPickerEntity(user);
                searchTree.AddEntity(entity);
            }
        }
예제 #27
0
        static public PickerEntity CreatePickerEntity(int id, string value)
        {
            var pe = new PickerEntity
            {
                Key         = id.ToString(),
                DisplayText = value
            };

            return(pe);
        }
예제 #28
0
 public void AddToContext(string ListName, string FieldName, PickerEntity NewPicker)
 {
     string _key = "Picker_" + SPContext.Current.Web.CurrentUser.ID + ListName + FieldName;
     ArrayList alOptions = new ArrayList();
     if (Context.Application[_key] != null)
     {
         alOptions = (ArrayList)Context.Application[_key];
     }
     alOptions.Add(NewPicker);
     Context.Application[_key] = alOptions;
 }
예제 #29
0
        protected override void FillResolve(Uri context, string[] entityTypes, Microsoft.SharePoint.Administration.Claims.SPClaim resolveInput, List <Microsoft.SharePoint.WebControls.PickerEntity> resolved)
        {
            //PickerEntity[] baseResolved = base.Resolve(context, entityTypes, resolveInput);
            //List<SPClaim> claims = base.GetClaimsForEntity(context,resolveInput).ToList<SPClaim>();
            //FillClaimsForEntity(context, resolveInput, claims);
            string provider = resolveInput.OriginalIssuer.ToLower();

            //if (resolveInput.OriginalIssuer.Contains("zimbramembershipprovider") || resolveInput.OriginalIssuer.Contains("zimbraroleprovider") || resolveInput.OriginalIssuer.Contains("zimbraclaimprovider"))
            //if (provider.Contains("zimbramembershipprovider") || provider.Contains("zimbraroleprovider") || provider.Contains("zimbraclaimprovider"))
            if (provider.Contains("zimbraclaimprovider"))
            {
                if (resolved.Count == 0)// || resolved.Count == 1)
                {
                    string         identifier = resolveInput.Value.Split('|').Last();
                    MembershipUser user;
                    if (!string.IsNullOrWhiteSpace(identifier))
                    {
                        user = Provider.GetUser(identifier, true);
                    }
                    else
                    {
                        user = Provider.GetUser(resolveInput.Value, true);
                    }

                    //MembershipUser user = Provider.GetUser(resolveInput.Value, true);
                    ZimbraMembershipUser zuser = null;
                    if (user != null && user.GetType() == typeof(ZimbraMembershipUser))
                    {
                        zuser = user as ZimbraMembershipUser;
                    }

                    if (zuser != null)
                    {
                        PickerEntity pe = CreatePickerEntity();
                        //pe.Claim = base.CreateClaim(SPClaimTypes.UserLogonName, zuser.uid, "http://www.w3.org/2001/XMLSchema#string");
                        pe.Claim       = resolveInput;
                        pe.DisplayText = zuser.displayName;
                        pe.EntityType  = SPClaimEntityTypes.User;
                        pe.IsResolved  = true;
                        pe.EntityData[PeopleEditorEntityDataKeys.DisplayName] = zuser.displayName;
                        pe.EntityData[PeopleEditorEntityDataKeys.Email]       = zuser.Email;
                        pe.EntityData[PeopleEditorEntityDataKeys.SIPAddress]  = zuser.Email;
                        pe.EntityData[PeopleEditorEntityDataKeys.UserId]      = zuser.uid;
                        pe.EntityData[PeopleEditorEntityDataKeys.AccountName] = zuser.uid;
                        //pe.ProviderName = resolveInput.OriginalIssuer;
                        //pe.Description = resolveInput.OriginalIssuer + ":" + zuser.displayName;
                        List <SPClaim> claims = base.GetClaimsForEntity(context, pe.Claim).ToList <SPClaim>();
                        resolved.Add(pe);
                    }
                }
                //FillResolve(context, entityTypes, resolveInput.Value, resolved);
                //throw new NotImplementedException();
            }
        }
예제 #30
0
        /// <summary>
        /// Resolves the picker entity.
        /// </summary>
        /// <param name="needsValidation">The needs validation.</param>
        public void ResolvePickerEntity(PickerEntity needsValidation)
        {
            string value = InternalDBResolver(needsValidation.Key);

            if (value != null)
            {
                needsValidation.Description = value;
                needsValidation.DisplayText = value;
                needsValidation.IsResolved  = true;
            }
        }
예제 #31
0
        private PickerEntity GetEntity(SPListItem item)
        {
            FieldLookupWithPickerPropertyBag propertyBag = new FieldLookupWithPickerPropertyBag(this.CustomProperty);

            PickerEntity entity = new PickerEntity();

            entity.DisplayText = item[propertyBag.FieldId].ToString();
            entity.Key         = item.ID.ToString();
            entity.Description = entity.DisplayText;
            entity.IsResolved  = true;
            return(entity);
        }
        protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, Microsoft.SharePoint.WebControls.SPProviderHierarchyTree searchTree)
        {
            //Make sure search is asking for the type of entity we return; site collection admin won't for example.
            if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole))
            {
                return;
            }

            //Counter to track what node we are in.
            int teamNode = -1;

            //Nodes where we will stick our matches.
            Microsoft.SharePoint.WebControls.SPProviderHierarchyNode matchNode = null;

            //Look to see if the value that is typed in matches any of our teams.
            foreach (string team in ourTeams)
            {
                //Increment team node tracker.
                teamNode += 1;

                if (team.ToLower().StartsWith(searchPattern.ToLower()))
                {
                    //We have a match, create a matching entity.
                    PickerEntity pe = GetPickerEntity(team);

                    //Add the team node where it should be displayed too.
                    if (!searchTree.HasChild(teamKeys[teamNode]))
                    {
                        //Create the node so we can show our match in there too.
                        matchNode = new
                                    SPProviderHierarchyNode(SqlClaims.ProviderInternalName,
                                                            teamLabels[teamNode],
                                                            teamKeys[teamNode],
                                                            true);

                        //Add it to the tree.
                        searchTree.AddChild(matchNode);
                    }
                    else
                    {
                        //Get the node for this team.
                        matchNode = searchTree.Children.Where(theNode =>
                                                              theNode.HierarchyNodeID == teamKeys[teamNode]).First();
                    }

                    //Add the match to our node.
                    matchNode.AddEntity(pe);
                }
            }
        }
        protected virtual PickerEntity GetRolePickerEntity(string role)
        {
            PickerEntity pe = CreatePickerEntity();

            pe.DisplayText = string.Format("'{0}' Role", role);
            pe.Description = string.Format("[{0}] '{1}' Role", ProviderInternalName, role);
            pe.EntityType  = SPClaimEntityTypes.FormsRole;
            pe.Claim       = new SPClaim(RoleClaimType, role,
                                         Microsoft.IdentityModel.Claims.ClaimValueTypes.String,
                                         SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, this.associatedSPTrustedLoginProvider.Name));
            pe.IsResolved      = true;
            pe.EntityGroupName = this.pickerEntityGroupName;
            return(pe);
        }
예제 #34
0
        public override PickerEntity GetEntity(DataRow row)
        {
            PickerEntity entity = new PickerEntity();
            entity.DisplayText = row[propertyBag.FieldId.ToString()].ToString();
            entity.Key = row[SPBuiltInFieldId.ID.ToString()].ToString();
            entity.Description = entity.DisplayText;
            entity.IsResolved = true;

            foreach (DataColumn col in row.Table.Columns)
            {
                entity.EntityData.Add(col.Caption, row[col]);
            }
            return entity;
        }
        public override PickerEntity GetEntity(DataRow dataRow)
        {
            if (dataRow == null)
                return null;

            var entity = new PickerEntity
                             {
                                 Key = Convert.ToString(dataRow["ID"]),
                                 DisplayText = Convert.ToString(dataRow["Value"]),
                                 IsResolved = true
                             };

            return entity;
        }
        private PickerEntity GetPickerEntityADFS(string token)
        {
            PickerEntity entity = CreatePickerEntity();

            entity.Claim       = new SPClaim(DBClaimType, token, DBClaimValueType, SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, SPTrustedIdentityTokenIssuerName)); //using ADFS Claim
            entity.Description = token;
            entity.DisplayText = token;
            entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = token;
            entity.EntityData[PeopleEditorEntityDataKeys.Email]       = token;
            entity.EntityData[PeopleEditorEntityDataKeys.AccountName] = token;
            entity.EntityType = SPClaimEntityTypes.User;
            entity.IsResolved = true;
            return(entity);
        }
예제 #37
0
        public override PickerEntity ValidateEntity(PickerEntity needsValidation)
        {
            PickerEntity entity = needsValidation;

            LookupFieldWithPickerPropertyBag propertyBag = new LookupFieldWithPickerPropertyBag(this.CustomProperty);

            if (!string.IsNullOrEmpty(needsValidation.DisplayText))
            {
                    // Get reference to LookUp List
                    SPList list = null;
                    SPWeb ObjWeb = SPContext.Current.Web;
                    list = ObjWeb.Lists[propertyBag.ListId];

                    SPQuery queryById = new SPQuery();
                    queryById.ViewAttributes = "Scope=\"Recursive\"";
                    queryById.Query = string.Format("<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">{0}</Value></Eq></Where>", needsValidation.Key);
                    SPListItemCollection items = list.GetItems(queryById);
                    if (items.Count > 0)
                    {
                        entity = this.GetEntity(items[0]);
                    }
                    else
                    {
                        SPQuery queryByTitle = new SPQuery();
                        queryByTitle.Query = string.Format("<Where><Eq><FieldRef ID=\"{0}\"/><Value Type=\"Text\">{1}</Value></Eq></Where>", propertyBag.FieldId, needsValidation.DisplayText);
                        queryByTitle.ViewAttributes = "Scope=\"Recursive\"";
                        items = list.GetItems(queryByTitle);
                        if (items.Count > 0)
                        {
                            entity = this.GetEntity(items[0]);
                        }
                    }
                    if (this.Entities != null)
                    {
                        Context.Application["Picker_" + SPContext.Current.Web.CurrentUser.ID + propertyBag.ListName + propertyBag.FieldName] = this.Entities;
                        //AddToContext(propertyBag.ListName, propertyBag.FieldName, (PickerEntity)base.EditorControl.Entities[0]);
                    }
            }
            return entity;
        }
        public override PickerEntity GetEntity(DataRow row)
        {
            PickerEntity entity = new PickerEntity();
            entity.DisplayText = row[propertyBag.FieldId.ToString()].ToString();
            entity.Key = row[SPBuiltInFieldId.ID.ToString()].ToString();
            entity.Description = entity.DisplayText;
            entity.IsResolved = true;

            foreach (DataColumn col in row.Table.Columns)
            {
                foreach (string internalName in propertyBag.SearchFields)
                {
                    if (internalName == col.ExtendedProperties["InternalName"].ToString())
                    {
                        entity.EntityData.Add(col.ColumnName, row[col]);
                        break;
                    }
                }
            }

            return entity;
        }
        private void SetFieldControlValue(object value)
        {
            LookupFieldWithPicker lookupFieldPicker = (LookupFieldWithPicker)this.Field;
            ArrayList alList = new ArrayList();
            PickerEntity ObjPickerEntity = new PickerEntity();

            //Clear all existing Entities from the lookup
            this.lookupEditor.Entities.Clear();

            ObjPickerEntity = this.lookupEditor.ValidateEntity(ObjPickerEntity);
            {
                SPFieldLookupValueCollection lookupValues = value as SPFieldLookupValueCollection;
                foreach (SPFieldLookupValue lookupValue in lookupValues)
                {
                    PickerEntity entity = this.lookupEditor.GetEntityById(lookupValue.LookupId);
                    if (entity != null)
                    {
                        alList.Add(entity);
                    }
                }
            }
            Context.Application["Picker_" + Web.CurrentUser.ID + this.List.Title + this.Field.InternalName] = alList;
            this.lookupEditor.UpdateEntities(alList);
        }
        protected void ddlReportingTo_SelectedIndexChanged(object sender, EventArgs e)
        {
            // ddlReportingTo.SelectedItem.Text = spv.LookupValue;
            //DropDownList customer =
            // ddlReportingTo.Items.FindByText(spv.LookupValue).Selected = true;
            using (var site = new SPSite(SPContext.Current.Site.Url))
            {
                using (var web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    var empid = Request.QueryString["EmpId"];

                    var emplist = web.Lists.TryGetList("Employee Screen");
                    var empitem = emplist.GetItemById(Convert.ToInt16(empid));
                    empSPid.Value = empid;
                    var entity = new PickerEntity
                    {
                        DisplayText =
                            new SPFieldUserValue(web, empitem["Employee Name"].ToString()).User
                            .
                            LoginName
                    };

                    //var spv = new SPFieldLookupValue(empitem["Manager"].ToString());
                    //ddlReportingTo.SelectedItem.Text = spv.LookupValue;

                   txtempusername.Text = web.AllUsers[entity.DisplayText].Name;

                    //SPUser user = web.CurrentUser;
                    //hdnCurrentUsername.Value = user.Name;

                    var leavelist = SPContext.Current.Web.Lists.TryGetList(Utilities.LeaveRequest);
                    var leavelistitems = GetListItemCollection(leavelist,  "RequestedFrom", txtempusername.Text,"Status","Pending");

                    if (leavelistitems != null && leavelistitems.Count > 0)
                    {
                        LblError.Text = "Make sure that no pending leave requests for previous manager";
                        BtnRegister.Enabled = false;
                    }
                    else
                    {
                        BtnRegister.Enabled = true;
                    }

                }
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string leaveSDate = ((TextBox)(dateTimeStartDate.Controls[0])).Text;
            string leaveEDate = ((TextBox)(dateTimeEndDate.Controls[0])).Text;

            if (!ValidateDate(leaveSDate, "MM/dd/yyyy"))
            {
                lblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                lblError.Text += "<br/>";
                dateTimeStartDate.ClearSelection();
                dateTimeStartDate.Focus();
                return;

            }
            if (!ValidateDate(leaveEDate, "MM/dd/yyyy"))
            {
                lblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                lblError.Text += "<br/>";
                dateTimeEndDate.ClearSelection();
                dateTimeEndDate.Focus();
                return;

            }
            try
            {
                SetDate();

                lblError.Text = string.Empty;

                if (txtDuration.Value != "0" && txtDuration.Value != "")
                {
                    if (decimal.Parse(txtDuration.Value) > 0)
                    {
                        using (var site = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (var web = site.OpenWeb())
                            {
                                SPUser user = web.CurrentUser;
                                hdnCurrentUsername.Value = user.Name;
                                var list = web.Lists.TryGetList(Utilities.CompoffList);
                                web.AllowUnsafeUpdates = true;

                                SPListItem newItem = list.Items.Add();

                                var entity = new PickerEntity
                                {
                                    DisplayText =
                                        new SPFieldUserValue(web, hdnReportingTo.Value)
                                        .
                                        User.
                                        LoginName
                                };

                                newItem["RequestedFrom"] = web.AllUsers[web.CurrentUser.LoginName];
                                newItem["RequestedTo"] = web.AllUsers[entity.DisplayText];

                                newItem["Worked for"] = txtPurpose.Text;
                                newItem["EmpID"] = lblEmpID.Text;
                               // newItem["Desgination"] = lblDesgination.Text;
                                //newItem["Department"] = lblDepartment.Text;
                                newItem["Duration"] = txtDuration.Value;
                                newItem["Year"] = hdnCurrentYear.Value;

                                newItem["Starting Date"] = DateTime.Parse(leaveSDate);
                                newItem["Ending Date"] = DateTime.Parse(leaveEDate);
                                //dateTimeEndDate.SelectedDate;

                                newItem.Update();

                                Server.Transfer(Request.RawUrl);

                            }
                        }
                    }
                    else
                    {
                        lblError.Text = "Select Valid dates";
                    }
                }
                else
                {
                    lblError.Text = "Select Valid dates";
                }

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
예제 #42
0
        private void BindPeoplePicker(PeopleEditor ppEditor, List<string> list)
        {
            string users = "";
            System.Collections.ArrayList entityArrayList = new System.Collections.ArrayList();
            PickerEntity entity = new PickerEntity();
            foreach (var item in list)
            {
                entity.Key = item;
                // this can be omitted if you're sure of what you are doing
                entity = ppEditor.ValidateEntity(entity);
                entityArrayList.Add(entity);
                users += item + ",";
            }

            //ppEditor.UpdateEntities(entityArrayList);
            if (list.Count > 0)
                ppEditor.CommaSeparatedAccounts = users.Remove(users.LastIndexOf(","), 1);
        }
예제 #43
0
        /// <summary>
        /// A method used to validate the resolve multiple claim response. 
        /// </summary>
        /// <param name="resolveMultipleClaimResult">A parameter represents the resolve multiple claim result.</param>       
        private void ValidateResolveMultipleClaimResponseData(PickerEntity[] resolveMultipleClaimResult)
        {
            XmlElement xmlResponse = SchemaValidation.LastRawResponseXml;
            bool isResponseValid = SchemaValidation.ValidationResult == ValidationResult.Success;

            // The response have been received successfully, then the following requirement can be captured.
            Site.CaptureRequirementIfIsTrue(
                isResponseValid,
                348,
                @"[In ResolveMultipleClaim] The following is the WSDL port type specification of the ResolveMultipleClaim WSDL operation.
<wsdl:operation name=""ResolveMultipleClaim"" xmlns:wsdl=""http://schemas.xmlsoap.org/wsdl/"">
  <wsdl:input wsam:Action=""http://schemas.microsoft.com/sharepoint/claims/IClaimProviderWebService/ResolveMultipleClaim"" message=""tns:IClaimProviderWebService_ResolveMultipleClaim_InputMessage"" xmlns:wsaw=""http://www.w3.org/2006/05/addressing/wsdl""/>
  <wsdl:output wsam:Action=""http://schemas.microsoft.com/sharepoint/claims/IClaimProviderWebService/ResolveMultipleClaimResponse"" message=""tns:IClaimProviderWebService_ResolveMultipleClaim_OutputMessage"" xmlns:wsaw=""http://www.w3.org/2006/05/addressing/wsdl""/>
</wsdl:operation>");

            Site.CaptureRequirementIfIsTrue(
                isResponseValid,
                349,
                @"[In ResolveMultipleClaim] The protocol client sends an IClaimProviderWebService_ResolveMultipleClaim_InputMessage (section 3.1.4.11.1.1) request WSDL message and the protocol server responds with an IClaimProviderWebService_ResolveMultipleClaim_OutputMessage (section 3.1.4.11.1.2) response message.");

            // If the server response is validated successfully, and the ResolveMultipleClaimResponse has returned, MS-CPSWS_R359 can be verified.
            Site.CaptureRequirementIfIsTrue(
                this.ResponseExists(xmlResponse, "ResolveMultipleClaimResponse"),
                359,
                @"[In IClaimProviderWebService_ResolveMultipleClaim_OutputMessage] The SOAP body contains the ResolveMultipleClaimResponse element.");

            // The response have been received successfully, then the following requirement can be captured.
            Site.CaptureRequirementIfIsTrue(
                isResponseValid,
                367,
                @"[In ResolveMultipleClaimResponse] The ResolveMultipleClaimResponse element specifies the result data for the ResolveMultipleClaim WSDL operation.
<xs:element name=""ResolveMultipleClaimResponse"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
  <xs:complexType>
    <xs:sequence>
      <xs:element minOccurs=""0"" maxOccurs=""1"" name=""ResolveMultipleClaimResult"" type=""tns:ArrayOfPickerEntity""/>
    </xs:sequence>
  </xs:complexType>
</xs:element>");

            if (resolveMultipleClaimResult.Length != 0)
            {
                this.ValidateArrayOfPickerEntityComplexType();
            }
        }
        private void PopulateDelegation(Delegation delegation)
        {
            delegationID.Value = delegation.Id.ToString();
            btnSubmit.Text = "Update";
            SPUser user = SPContext.Current.Web.Site.RootWeb.AllUsers.GetByID(delegation.AssignedToId.Value);

            PickerEntity entity = new PickerEntity();
            entity.Key = user.LoginName;

            ArrayList entityArrayList = new ArrayList();
            entityArrayList.Add(entity);
            spPeoplePicker.UpdateEntities(entityArrayList);
            calDelegateFrom.SelectedDate = delegation.StartDate.Value;
            calDelegateTo.SelectedDate = delegation.EndDate.Value;
        }
        internal DataTable GetEmployeeLeaves()
        {
            DataTable dataTable = EmployeeLeavesStructure();
            try
            {
                var employeeList = SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeScreen).GetItems();
                //GetListItemCollection(SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeScreen),Utilities.EmployeeType, "Permanent");
                foreach (SPListItem employee in employeeList)
                {
                    DataRow dataRow = dataTable.NewRow();

                    dataRow["Employee Id"] = employee["Employee ID"].ToString();
                    var entity = new PickerEntity
                                     {
                                         DisplayText =
                                             new SPFieldUserValue(SPContext.Current.Web,
                                                                  employee["Employee Name"].ToString()).User.
                                             Name
                                     };
                    var entityRep = new PickerEntity
                                        {
                                            DisplayText =
                                                new SPFieldUserValue(SPContext.Current.Web,
                                                                     employee[Utilities.Manager].ToString()).User.
                                                Name
                                        };
                    dataRow["Employee Name"] = entity.DisplayText.ToString();
                    dataRow["Reporting To"] = entityRep.DisplayText.ToString();
                    var employeeLeaveList =
                        GetListItemCollection(SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeLeaves),
                                              "Employee ID", employee["Employee ID"].ToString(), "Year",
                                              hdnCurrentYear.Value);
                    foreach (SPListItem empleaves in employeeLeaveList)
                    {
                        var spv = new SPFieldLookupValue(empleaves[Utilities.LeaveType].ToString());
                        decimal leaveBalance = 0;
                        decimal leaveDays = 0;
                        var leaveTypeList = GetListItemCollection(SPContext.Current.Web.Lists.TryGetList(Utilities.LeaveDays),
                                               "Leave Type", spv.LookupValue.Trim(), Utilities.EmployeeType,
                                               "Permanent");
                        foreach (SPListItem leavetype in leaveTypeList)
                        {
                            leaveDays = decimal.Parse(leavetype["Leave Days"].ToString());
                        }

                        if (employee[Utilities.EmployeeType].ToString().Trim() == "Permanent")
                        {

                            if (spv.LookupValue.Trim() == "Paid Leave")
                            {

                                decimal leaves = decimal.Parse(empleaves["Leave Balance"].ToString()) + (leaveDays * 12);

                                if (leaves % 1 == 0)
                                {
                                    int noOfleaves = Convert.ToInt16(leaves);
                                    leaveBalance = noOfleaves;
                                }
                                else
                                {
                                    leaveBalance = leaves;
                                }

                            }
                            else if (spv.LookupValue.Trim() == "Comp off")
                            {
                                leaveBalance = decimal.Parse(empleaves["Leave Balance"].ToString());
                            }
                            else if (spv.LookupValue.Trim() == "Optional")
                            {
                                leaveBalance = leaveDays;
                            }
                            else
                            {
                                decimal leaves = (leaveDays * 12);
                                if (leaves % 1 == 0)
                                {
                                    int noOfleaves = Convert.ToInt16(leaves);
                                    leaveBalance = noOfleaves;
                                }
                                else
                                {
                                    leaveBalance = leaves;
                                }

                                //leaveBalance = (leaveDays * 12);
                            }
                        }
                        else
                        {
                            if (spv.LookupValue.Trim() == "Paid Leave")
                            {
                                leaveBalance = decimal.Parse(empleaves["Leave Balance"].ToString());
                            }
                            else if (spv.LookupValue.Trim() == "Comp off")
                            {
                                leaveBalance = decimal.Parse(empleaves["Leave Balance"].ToString());
                            }
                            else if (spv.LookupValue.Trim() == "Optional")
                            {
                                leaveBalance = leaveDays;
                            }
                            else
                            {
                                leaveBalance = 0;

                            }
                        }
                        dataRow[spv.LookupValue.Trim()] = leaveBalance;
                    }
                    dataTable.Rows.Add(dataRow);
                }
            }
            catch (Exception e)
            {
                lblError.Text = e.Message;
            }
            return dataTable;
        }
 private static bool IsEntityUser(PickerEntity entity)
 {
     return entity.EntityData != null && entity.EntityData.Count > 0 &&
            entity.EntityData["PrincipalType"].ToString() == "User";
 }
        /// <summary>
        /// A method used to resolve a list of claims to picker entities using a list of claims providers.
        /// </summary>
        /// <param name="providerNames">A parameter represents a list of provider names.</param>
        /// <param name="principalType">A parameter represents which type of picker entities to be included in the result.</param>
        /// <param name="resolveInput">A parameter represents a list of claims to be resolved.</param>
        /// <returns>A return value represents a list of picker entities.</returns>
        public PickerEntity[] ResolveMultipleClaim(ArrayOfString providerNames, SPPrincipalType principalType, SPClaim[] resolveInput)
        {
            PickerEntity[] responseOfResolveMultipleClaim = new PickerEntity[0];
            try
            {
                responseOfResolveMultipleClaim = this.cpswsClient.ResolveMultipleClaim(providerNames, principalType, resolveInput);
                this.CaptureTransportRelatedRequirements();
            }
            catch (FaultException faultEX)
            {
                this.Site.Log.Add(
                                LogEntryKind.Debug,
                                @"There is an exception generated when calling [ResolveMultipleClaim] method:\r\n{0}",
                                faultEX.Message);
                this.CaptureTransportRelatedRequirements();
                this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
                throw;
            }

            this.ValidateResolveMultipleClaimResponseData(responseOfResolveMultipleClaim);

            return responseOfResolveMultipleClaim;
        }
        public void EmployeeDetails()
        {
            try
            {
                if (Request.QueryString["EmpId"] != null)
                {
                    using (var site = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (var web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            var empid = Request.QueryString["EmpId"];

                            var emplist = web.Lists.TryGetList("Employee Screen");
                            var empitem = emplist.GetItemById(Convert.ToInt16(empid));
                            empSPid.Value = empid;

                            txtempid.Text = empitem["Title"].ToString();
                            txtfristname.Text = empitem["First Name"].ToString();
                            txtlastname.Text = empitem["Last Name"].ToString();
                            //TxtContact.Text = empitem["Mobile"].ToString();
                            var entity = new PickerEntity
                                             {
                                                 DisplayText =
                                                     new SPFieldUserValue(web, empitem["Employee Name"].ToString()).User
                                                     .
                                                     LoginName
                                             };

                            txtempusername.Text = entity.DisplayText;

                            //  peoplepickeremp.Entities.Add(entity);
                            DdlDep.SelectedItem.Text = empitem["Department"].ToString();

                            DdlDesignation.SelectedItem.Text = empitem["Designation"].ToString();
                            DdlEmptype.SelectedItem.Text = empitem["Employee Type"].ToString();
                            hdnCurrentEmpType.Value = empitem["Employee Type"].ToString();
                            //Txtmail.Text = empitem["Email"].ToString();
                            //      DtDOB.SelectedDate = Convert.ToDateTime(empitem["DOB"].ToString());
                            DtDoj.SelectedDate = Convert.ToDateTime(empitem["Date of Join"].ToString());

                            if (empitem["Employee Type"].ToString().Trim() == "Permanent")
                            {
                                if (empitem["Date of Permanent"] != null)
                                    DtDOP.SelectedDate = Convert.ToDateTime(empitem["Date of Permanent"].ToString());
                                //divdop.Visible = true;
                                chkPrePL.Enabled = false;
                            }
                            //else
                            //{
                            //    divdop.Visible = false;
                            //}
                            var spv = new SPFieldLookupValue(empitem["Manager"].ToString());

                            // ddlReportingTo.SelectedItem.Text = spv.LookupValue;
                            //DropDownList customer =
                            ddlReportingTo.Items.FindByText(spv.LookupValue).Selected = true;
                            //if (customer != null)
                            //{
                            //    customer.Selected = true;

                            //}
                            if (empitem["Status"].ToString().Trim() != "Active")
                            {
                                BtnRegister.Enabled = false;
                            }

                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LblError.Text = ex.Message;
            }
        }
예제 #49
0
        private void UpdateControls(bool IsEditCase)
        {
            try
            {
                using (SPSite oSPsite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        this.targetDate_dtc.SelectedDate = DateTime.Now.Date;
                        this.msaDate_dtc.SelectedDate = DateTime.Now.Date;
                        this.msaDate_dtc.Enabled = false;

                        //Ristrict users
                        //string groupName = Utility.GetValueByKey("ADGroup");

                        //if (!String.IsNullOrEmpty(groupName))
                        //{
                        //    //this.responsiblePerson_PeopleEditor.PrincipalSource = null;
                        //    var spGroup = oSPWeb.Groups[groupName];
                        //    if (spGroup != null)
                        //    {
                        //        this.responsiblePerson_PeopleEditor.SharePointGroupID = spGroup.ID;
                        //    }
                        //}
                        //End

                        if (!IsEditCase)
                        {
                            SPUser CurrentUser = oSPWeb.CurrentUser;
                            if (CurrentUser != null && this.auditedBy_PeopleEditor.Entities.Count == 0)
                            {
                                // Clear existing users from control
                                this.auditedBy_PeopleEditor.Entities.Clear();

                                // PickerEntity object is used by People Picker Control
                                PickerEntity UserEntity = new PickerEntity();

                                // CurrentUser is SPUser object
                                UserEntity.DisplayText = CurrentUser.Name;
                                UserEntity.Key = CurrentUser.LoginName;

                                // Add PickerEntity to People Picker control
                                this.auditedBy_PeopleEditor.Entities.Add(this.auditedBy_PeopleEditor.ValidateEntity(UserEntity));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSAForm->UpdateControls)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);

                message_div.InnerHtml = "Something went wrong!!! Please Contact the administrator.";
                DisableControls();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            cn.ConnectionString = ConfigurationManager.AppSettings["clr_ConStr"]; // get appSettings for current appln configuretion
            selectCommand = cn.CreateCommand();

            if (!Page.IsPostBack)
            {
                try
                {
                    if (Request.QueryString["empid"] != null)
                    {
                        if (Page.Request.QueryString["DeptName"] == null)
                        {
                            trddlDepartment.Visible = false;
                        }
                        ImgbtnClear.Visible = false;
                        // get EmployeeId from QueryString
                        string strEmpId = Request.QueryString["empid"];

                        selectCommand.Parameters.Add(new SqlParameter("@EmployeeID", strEmpId)); //Parameters for stored proc
                        selectCommand.CommandType = CommandType.StoredProcedure;    //command through stored proc
                        selectCommand.CommandText = "SP_GetEmployee_LoadByEmpID";      // stored proc name
                        da.SelectCommand = selectCommand;
                        da.Fill(dtEmployeeList);
                        if (dtEmployeeList != null)
                        {
                            if (dtEmployeeList.Rows.Count > 0)
                            {
                                if (dtEmployeeList.Rows[0]["EmployeeID"] != null)
                                {
                                    ArrayList _arrayList = new ArrayList();
                                    SPWeb web = SPContext.Current.Web;
                                    web.AllowUnsafeUpdates = true;
                                    SPUser User = null;

                                    User = web.EnsureUser(dtEmployeeList.Rows[0]["EmployeeID"].ToString());
                                    User = web.SiteUsers.GetByID(User.ID);

                                    PickerEntity pen = new PickerEntity();
                                    pen.Key = User.LoginName;
                                    pen.IsResolved = true;
                                    _arrayList.Add(pen);
                                    ppleditEmployeeID.UpdateEntities(_arrayList);
                                    txtEmployeeID.Text = ppleditEmployeeID.Accounts.Count > 0 ? ppleditEmployeeID.Accounts[0].ToString() : "";
                                }
                                txtEmployeeRole.Text = dtEmployeeList.Rows[0]["RoleName"].ToString();
                            }
                        }
                    }
                    else if (Page.Request.QueryString["DeptName"] != null)
                    {
                        trddlDepartment.Visible = true;

                        ddlDepartment.DataSource = GetAllDept();  // Call GetAll Department Function
                        ddlDepartment.DataTextField = "Name";
                        ddlDepartment.DataValueField = "DeptID";
                        ddlDepartment.DataBind();
                        ddlDepartment.Items.Insert(0, new ListItem("-- Select --"));

                        ddlDepartment.SelectedIndex = ddlDepartment.Items.IndexOf(ddlDepartment.Items.FindByText(Page.Request.QueryString["DeptName"].ToString()));
                    }
                    else
                    {
                        trddlDepartment.Visible = false;
                    }
                }
                catch (Exception ex)
                {
                    lblMsg.Visible = true;
                    lblMsg.ForeColor = System.Drawing.Color.FromName("#FF0000");
                    lblMsg.Text = ex.Message;
                    cn.Close();
                }
            }
        }
        protected void BtnUpdateClick(object sender, EventArgs e)
        {
            string dOP = ((TextBox)(DtDOP.Controls[0])).Text;
            string dOJ = ((TextBox)(DtDoj.Controls[0])).Text;
            //   string dOB = ((TextBox)(DtDOB.Controls[0])).Text;

            //if (DdlEmptype.SelectedItem.Value.Trim() == "Permanent")
            //{

            //    if (DtDOP.IsDateEmpty)
            //    {
            //        LblError.Text = "Please Enter the valid DOP.";
            //        LblError.Text += "<br/>";
            //        divdop.Visible = true;
            //        return;
            //    }
            //    else if (!ValidateDate(DtDOP.SelectedDate.ToShortDateString(), "MM/dd/yyyy"))
            //    {
            //        LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
            //        LblError.Text += "<br/>";
            //        divdop.Visible = true;
            //        DtDOP.ClearSelection();
            //        DtDOP.Focus();
            //        return;

            //    }
            //    else if (DtDOP.SelectedDate > DateTime.Now)
            //    {
            //        LblError.Text = "DOP should be Less than or equal to today.";
            //        LblError.Text += "<br/>";
            //        divdop.Visible = true;
            //        DtDOP.ClearSelection();
            //        DtDOP.Focus();
            //        return;
            //    }
            //}
            //if (!ValidateDate(DtDoj.SelectedDate.ToShortDateString(), "MM/dd/yyyy"))
            //{
            //    LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
            //    LblError.Text += "<br/>";
            //    DtDoj.ClearSelection();
            //    DtDoj.Focus();
            //    return;

            //}
            //else if (DtDoj.SelectedDate > DateTime.Now)
            //{
            //    LblError.Text = "DOP should be Less than or equal to today.";
            //    LblError.Text += "<br/>";
            //    divdop.Visible = true;
            //    DtDoj.ClearSelection();
            //    DtDoj.Focus();
            //    return;
            //}
            //if (!ValidateDate(DtDOB.SelectedDate.ToShortDateString(), "MM/dd/yyyy"))
            //{
            //    LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
            //    LblError.Text += "<br/>";
            //    DtDOB.ClearSelection();
            //    DtDOB.Focus();
            //    return;

            //}
            //else if (DtDOB.SelectedDate > DateTime.Now)
            //{
            //    LblError.Text = "DOP should be Less than or equal to today.";
            //    LblError.Text += "<br/>";
            //    divdop.Visible = true;
            //    DtDOB.ClearSelection();
            //    DtDOB.Focus();
            //    return;
            //}
            //if (DtDOP.SelectedDate.Date < DtDoj.SelectedDate.Date)
            //{
            //    LblError.Text = "DOP should be greater than or equal to DOJ.";
            //    LblError.Text += "<br/>";
            //    return;
            //}
            //else if (DtDoj.SelectedDate.Date < DtDOB.SelectedDate.Date)
            //{
            //    LblError.Text = "DOJ should be greater than DOB.";
            //    LblError.Text += "<br/>";
            //    return;
            //}
            //if (!ValidateDate(dOB, "MM/dd/yyyy"))
            //{
            //    LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
            //    LblError.Text += "<br/>";
            //    DtDOB.ClearSelection();
            //    DtDOB.Focus();
            //    return;

            //}
            //else if (DateTime.Parse(dOB) > DateTime.Now)
            //{
            //    LblError.Text = "DOB should be Less than or equal to today.";
            //    LblError.Text += "<br/>";
            //    divdop.Visible = true;
            //    DtDOB.ClearSelection();
            //    DtDOB.Focus();
            //    return;
            //}
            if (string.IsNullOrEmpty(dOJ))
            {
                LblError.Text = "Please Enter the valid DOJ";
                LblError.Text += "<br/>";
                // divdop.Visible = true;
                return;
            }
            if (!ValidateDate(dOJ, "MM/dd/yyyy"))
            {
                LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                LblError.Text += "<br/>";
                DtDoj.ClearSelection();
                DtDoj.Focus();
                return;

            }
            else if (DateTime.Parse(dOJ) > DateTime.Now)
            {
                LblError.Text = "DOJ should be Less than or equal to today.";
                LblError.Text += "<br/>";
                divdop.Visible = true;
                DtDoj.ClearSelection();
                DtDoj.Focus();
                return;
            }
            if (DdlEmptype.SelectedItem.Value.Trim() == "Permanent")
            {

                if (string.IsNullOrEmpty(dOP))
                {
                    LblError.Text = "Please Enter the valid DOP.";
                    LblError.Text += "<br/>";
                    divdop.Visible = true;
                    return;
                }
                else if (!ValidateDate(dOP, "MM/dd/yyyy"))
                {
                    LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                    LblError.Text += "<br/>";
                    divdop.Visible = true;
                    DtDOP.ClearSelection();
                    DtDOP.Focus();
                    return;

                }
                else if (DateTime.Parse(dOP) > DateTime.Now)
                {
                    LblError.Text = "DOP should be Less than or equal to today.";
                    LblError.Text += "<br/>";
                    divdop.Visible = true;
                    DtDOP.ClearSelection();
                    DtDOP.Focus();
                    return;
                }
                else if (DateTime.Parse(dOP) < DateTime.Parse(dOJ))
                {
                    LblError.Text = "DOP should be greater than or equal to DOJ.";
                    LblError.Text += "<br/>";
                    return;
                }
            }

            //if (DateTime.Parse(dOJ) < DateTime.Parse(dOB))
            //{
            //    LblError.Text = "DOJ should be greater than DOB.";
            //    LblError.Text += "<br/>";
            //    return;
            //}

            try
            {
                using (var site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (var web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        var empid = empSPid.Value;
                        var emplist = web.Lists.TryGetList("Employee Screen");
                        var empitem = emplist.GetItemById(Convert.ToInt16(empid));

                        empitem["First Name"] = txtfristname.Text;
                        empitem["Last Name"] = txtlastname.Text;

                        // empitem["Employee Name"] = web.AllUsers[peoplepickeremp.Accounts[0].ToString()];
                        empitem["Employee Type"] = DdlEmptype.SelectedItem.Text;
                        empitem["Department"] = DdlDep.SelectedItem.Text;
                        empitem["Designation"] = DdlDesignation.SelectedItem.Text;
                        //empitem["Email"] = Txtmail.Text;
                        //empitem["Mobile"] = TxtContact.Text;
                        //empitem["Date of Join"] = DateTime.Parse(GetFormatedDate(dOJ));
                        //empitem["DOB"] = DtDOB.SelectedDate;
                        //empitem["Date of Permanent"] = DtDOP.SelectedDate;
                        empitem[Utilities.DateofJoin] = DateTime.Parse(GetFormatedDate(dOJ));// DtDoj.SelectedDate;
                        //  empitem[Utilities.DOB] = DateTime.Parse(GetFormatedDate(dOB)); //DtDOB.SelectedDate;
                        if (DdlEmptype.SelectedItem.Text.Trim() == "Permanent")
                        {
                            empitem["Date of Permanent"] = DateTime.Parse(GetFormatedDate(dOP));//DtDOP.SelectedDate;
                        }
                        PickerEntity entity = new PickerEntity();
                        entity.DisplayText = new SPFieldUserValue(web, ddlReportingTo.SelectedItem.Value).User.LoginName;
                        empitem[Utilities.Manager] = web.AllUsers[entity.DisplayText];

                        empitem.Update();

                        var leavelist = web.Lists.TryGetList(Utilities.LeaveDays);
                        var field = leavelist.Fields["Employee Type"];
                        var leaveDaysQuery = new SPQuery
                                                 {
                                                     Query =
                                                         @"<Where>
                                                <Eq>
                                                    <FieldRef Name='" +
                                                         field.InternalName + @"' />
                                                    <Value Type='Lookup'>" +
                                                         DdlEmptype.SelectedItem.Text + @"</Value>
                                                    </Eq>
                                                     </Where>"
                                                 };
                        var leaveDayscollection = leavelist.GetItems(leaveDaysQuery);

                        //int currentMonth = DateTime.Now.Month;
                        // int monthDiff = GetMonthDifference(currentMonth);

                        foreach (SPListItem leavedaItem in leaveDayscollection)
                        {
                            var emptype = new SPFieldLookupValue(leavedaItem["Employee Type"].ToString());
                            var leaveType = new SPFieldLookupValue(leavedaItem["Leave Type"].ToString());
                            var employeeleavelist = web.Lists.TryGetList(Utilities.EmployeeLeaves);

                            //var fieldempid = employeeleavelist.Fields["Employee ID"];
                            //var fieldempLeavetype = employeeleavelist.Fields["Leave Type"];
                            var lveType = new SPFieldLookupValue(leavedaItem["Leave Type"].ToString());

                            //var employeeleaveDaysQuery = new SPQuery
                            //{
                            //    Query = @"<Where><And><Eq><FieldRef Name=" + fieldempid.InternalName + " /><Value Type='Text'>" + txtempid.Text + "</Value></Eq><Eq><FieldRef Name=" + fieldempLeavetype.InternalName + " /><Value Type='Lookup'>" + leaveType.LookupValue
                            //    + "</Value></Eq></And></Where>"
                            //};

                            var empleaveCollection = GetListItemCollection(employeeleavelist, "Employee ID",
                                                                           txtempid.Text, "Leave Type",
                                                                           leaveType.LookupValue, "Year",
                                                                           hdnCurrentYear.Value);

                            //employeeleavelist.GetItems(employeeleaveDaysQuery);
                            if (empleaveCollection.Count == 0)
                            {
                                var empLeaveItem = employeeleavelist.Items.Add();

                                empLeaveItem["Employee ID"] = txtempid.Text;
                                empLeaveItem[Utilities.EmployeeName] = web.AllUsers[txtempusername.Text];
                                empLeaveItem["Leave Type"] = leavedaItem["Leave Type"].ToString();
                                if (lveType.LookupValue == "Comp off")
                                {
                                    empLeaveItem["Leave Balance"] = 0;
                                }
                                else if (lveType.LookupValue == "Optional")
                                {
                                    empLeaveItem["Leave Balance"] =
                                        decimal.Parse(leavedaItem["Leave Days"].ToString());
                                }
                                else if (lveType.LookupValue == "LOP")
                                {
                                    empLeaveItem["Leave Balance"] = 0;
                                }
                                else
                                {
                                    if (emptype.LookupValue.Trim() == "Permanent")
                                    {
                                        int dopMonth = DateTime.Parse(GetFormatedDate(dOP)).Month;// DtDOP.SelectedDate.Month;
                                        int monthDiff = GetMonthDifference(dopMonth);
                                        decimal leaves = decimal.Parse(leavedaItem["Leave Days"].ToString()) *
                                                         monthDiff;
                                        if (leaves % 1 == 0)
                                        {
                                            int noOfleaves = Convert.ToInt16(leaves);
                                            empLeaveItem["Leave Balance"] = noOfleaves;
                                        }
                                        else
                                        {
                                            empLeaveItem["Leave Balance"] = leaves;
                                        }
                                    }

                                        //if (emptype.LookupValue.Trim() == "Permanent")
                                    //    empLeaveItem["Leave Balance"] = decimal.Parse(leaveType["Leave Days"].ToString()) * monthDiff;
                                    else
                                    {
                                        decimal leaves = decimal.Parse(leavedaItem["Leave Days"].ToString()) *
                                                         1;
                                        if (leaves % 1 == 0)
                                        {
                                            int noOfleaves = Convert.ToInt16(leaves);
                                            empLeaveItem["Leave Balance"] = noOfleaves;
                                        }
                                        else
                                        {
                                            empLeaveItem["Leave Balance"] = leaves;
                                        }
                                    }
                                }
                                empLeaveItem["Leave utilized"] = 0;
                                empLeaveItem["Leave Requested"] = 0;
                                empLeaveItem["Reporting Manager"] = web.AllUsers[entity.DisplayText];
                                empLeaveItem[Utilities.Year] = hdnCurrentYear.Value;
                                empLeaveItem["Employee Type"] = DdlEmptype.SelectedValue;
                                empLeaveItem.Update();
                            }
                            else
                            {
                                if (hdnCurrentEmpType.Value.Trim() != "Permanent")
                                {
                                    foreach (SPListItem empleaveItem in empleaveCollection)
                                    {
                                        if (chkPrePL.Checked)
                                        {
                                            if (lveType.LookupValue != "Comp off" &&
                                                lveType.LookupValue != "Optional" && lveType.LookupValue != "LOP")
                                            {
                                                if (emptype.LookupValue.Trim() == "Permanent")
                                                {
                                                    int dopMonth = DateTime.Parse(GetFormatedDate(dOP)).Month;
                                                    //DtDOP.SelectedDate.Month;
                                                    int monthDiff = GetMonthDifference(dopMonth) - 1;
                                                    decimal leaves =
                                                        decimal.Parse(empleaveItem["Leave Balance"].ToString()) +
                                                        decimal.Parse(leavedaItem["Leave Days"].ToString()) *
                                                        monthDiff;
                                                    if (leaves % 1 == 0)
                                                    {
                                                        int noOfleaves = Convert.ToInt16(leaves);
                                                        empleaveItem["Leave Balance"] = noOfleaves;
                                                    }
                                                    else
                                                    {
                                                        empleaveItem["Leave Balance"] = leaves;
                                                    }
                                                }
                                                else
                                                {
                                                    decimal leaves =
                                                        decimal.Parse(empleaveItem["Leave Balance"].ToString()) +
                                                        decimal.Parse(leavedaItem["Leave Days"].ToString());
                                                    if (leaves % 1 == 0)
                                                    {
                                                        int noOfleaves = Convert.ToInt16(leaves);
                                                        empleaveItem["Leave Balance"] = noOfleaves;
                                                    }
                                                    else
                                                    {
                                                        empleaveItem["Leave Balance"] = leaves;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (lveType.LookupValue != "Comp off" &&
                                                lveType.LookupValue != "Optional" && lveType.LookupValue != "LOP")
                                            {
                                                if (emptype.LookupValue.Trim() == "Permanent")
                                                {
                                                    int dopMonth = DateTime.Parse(GetFormatedDate(dOP)).Month;
                                                    // DtDOP.SelectedDate.Month;
                                                    int monthDiff = GetMonthDifference(dopMonth);
                                                    decimal leaves =
                                                        decimal.Parse(leavedaItem["Leave Days"].ToString()) *
                                                        monthDiff;
                                                    if (leaves % 1 == 0)
                                                    {
                                                        int noOfleaves = Convert.ToInt16(leaves);
                                                        empleaveItem["Leave Balance"] = noOfleaves;
                                                    }
                                                    else
                                                    {
                                                        empleaveItem["Leave Balance"] = leaves;
                                                    }
                                                }

                                                else
                                                {
                                                    decimal leaves =
                                                        decimal.Parse(leavedaItem["Leave Days"].ToString());
                                                    if (leaves % 1 == 0)
                                                    {
                                                        int noOfleaves = Convert.ToInt16(leaves);
                                                        empleaveItem["Leave Balance"] = noOfleaves;
                                                    }
                                                    else
                                                    {
                                                        empleaveItem["Leave Balance"] = leaves;
                                                    }
                                                }
                                            }
                                        }
                                        empleaveItem[Utilities.Year] = hdnCurrentYear.Value;
                                        empleaveItem["Employee Type"] = DdlEmptype.SelectedValue;
                                        empleaveItem.Update();
                                    }
                                }
                            }
                        }
                        Context.Response.Write(
                            "<script type='text/javascript'>window.frameElement.commitPopup(); SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, '1');</script>");
                    }
                }
            }
            catch (Exception ex)
            {
                LblError.Text = ex.Message;
            }
        }
예제 #52
0
        private PickerEntity GetEntity(SPListItem item)
        {
            LookupFieldWithPickerPropertyBag propertyBag = new LookupFieldWithPickerPropertyBag(this.CustomProperty);

            PickerEntity entity = new PickerEntity();
            string displayValue = null;
            try
            {
                displayValue = item[propertyBag.FieldId] as String;
            }
            catch
            {
                //field has been deleted
            }

            if (displayValue != null
                && item.Fields[propertyBag.FieldId].Type == SPFieldType.Calculated
                && item[propertyBag.FieldId] != null
                && item[propertyBag.FieldId].ToString().Contains("#"))
            {
                entity.DisplayText = displayValue.ToString().Split('#')[1];
            }
            else
                entity.DisplayText = displayValue ?? "";
            entity.Key = item.ID.ToString();
            entity.Description = entity.DisplayText;
            entity.IsResolved = true;

            return entity;
        }
예제 #53
0
        public Control BuildValueSelectorControl(SPField field, string displayValue)
        {
            Control control = null;
            if (field == null) { control = new TextBox() { CssClass = "ms-long", Text = displayValue.ToString() }; }
            else
            {

                switch (field.Type)
                {
                    case SPFieldType.Boolean:

                        CheckBox checkbox = new CheckBox() { };
                        if (!string.IsNullOrEmpty(displayValue))
                        {
                            bool value;
                            if (bool.TryParse(displayValue, out value))
                            {
                                checkbox.Checked = value;
                            }

                        }
                        control = checkbox;
                        break;

                    case SPFieldType.File:
                    case SPFieldType.Calculated:
                    case SPFieldType.Computed:
                    case SPFieldType.Currency:
                    case SPFieldType.Integer:
                    case SPFieldType.Note:
                    case SPFieldType.Number:
                    case SPFieldType.Text:
                    case SPFieldType.URL:
                    case SPFieldType.Invalid:
                        control = new TextBox() { CssClass = "ms-long", Text = displayValue.ToString() };
                        break;
                    case SPFieldType.Choice:
                        SPFieldChoice fieldChoice = (SPFieldChoice)field;
                        DropDownList ddlValueChoice = new DropDownList();

                        foreach (string value in fieldChoice.Choices)
                        {
                            ddlValueChoice.Items.Add(new ListItem(value));
                        }

                        ddlValueChoice.Items.Insert(0, string.Empty);
                        ddlValueChoice.SelectedIndex = ddlValueChoice.Items.IndexOf(ddlValueChoice.Items.FindByValue(displayValue));
                        control = ddlValueChoice;
                        break;

                    case SPFieldType.DateTime:
                        SPFieldDateTime fieldDate = (SPFieldDateTime)field;
                        DateTimeControl dtcValueDate = new DateTimeControl();
                        dtcValueDate.DateOnly = (fieldDate.DisplayFormat == SPDateTimeFieldFormatType.DateOnly);
                        if (!string.IsNullOrEmpty(displayValue.ToString()))
                        {
                            DateTime date;
                            if (DateTime.TryParse(displayValue.ToString(), out date))
                            {
                                dtcValueDate.SelectedDate = Convert.ToDateTime(date).ToUniversalTime();
                            }
                        }

                        control = dtcValueDate;
                        break;

                    case SPFieldType.Lookup:
                        SPFieldLookup fieldLookup = (SPFieldLookup)field;
                        control = generateLookupControl(control, fieldLookup, displayValue);
                        break;

                    case SPFieldType.MultiChoice:
                        SPFieldMultiChoice fieldMultichoice = (SPFieldMultiChoice)field;
                        CheckBoxList chkValueMultiChoice = new CheckBoxList();
                        foreach (string value in fieldMultichoice.Choices)
                        {
                            ListItem item = new ListItem(value);
                            string[] arr = displayValue.Split(SEPARATOR.ToCharArray());

                            item.Selected = arr.Contains(value);

                            chkValueMultiChoice.Items.Add(item);
                        }
                        control = chkValueMultiChoice;

                        HtmlGenericControl div2 = new HtmlGenericControl("div");
                        div2.Attributes.Add("style", "overflow: auto;height:100px;width:100%;");
                        div2.Controls.Add(chkValueMultiChoice);

                        control = div2;
                        break;

                    case SPFieldType.User:
                        SPFieldUser fieldUser = (SPFieldUser)field;
                        PeopleEditor peoValue = new PeopleEditor() { CssClass = "ms-long" };
                        peoValue.MultiSelect = fieldUser.AllowMultipleValues;
                        peoValue.SelectionSet = (fieldUser.SelectionMode == SPFieldUserSelectionMode.PeopleOnly) ? "User" : "User,SPGroup ";
                        if (!string.IsNullOrEmpty(displayValue))
                        {
                            string[] arr = displayValue.Split(SEPARATOR.ToCharArray());

                            ArrayList list = new ArrayList();
                            foreach (string s in arr)
                            {
                                PickerEntity peMember = new PickerEntity();
                                string[] arrPeMember = s.Split('#');
                                peMember.Key = arrPeMember[1];
                                peMember = peoValue.ValidateEntity(peMember);
                                list.Add(peMember);
                            }
                            peoValue.UpdateEntities(list);
                        }
                        control = peoValue;
                        break;
                    default:
                        control = new TextBox() { CssClass = "ms-long", Text = displayValue };
                        break;
                }
            }
            control.ID = GENERIC_CONTROL_ID;
            return control;
        }
        protected void BtnSubmitClick(object sender, EventArgs e)
        {
            string leaveSDate = ((TextBox)(dateTimeStartDate.Controls[0])).Text;
            string leaveEDate = ((TextBox)(dateTimeEndDate.Controls[0])).Text;
            if (ddlTypeofLeave.SelectedItem.Text == "Optional")
            {

                leaveSDate = lstboxOptionalLeaves.SelectedValue;
                leaveEDate = lstboxOptionalLeaves.SelectedValue;
            }
            if (ddlTypeofLeave.SelectedIndex < 1)
            {
                lblError.Text = "Please select leave type.";
                lblError.Text += "<br/>";
                return;
            }
            if (string.IsNullOrEmpty(leaveSDate))
            {
                lblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                lblError.Text += "<br/>";

                return;
            }
            if (string.IsNullOrEmpty(leaveEDate))
            {
                lblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                lblError.Text += "<br/>";

                return;
            }
            if (!ValidateDate(leaveSDate, "MM/dd/yyyy"))
            {
                lblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                lblError.Text += "<br/>";
                if (ddlTypeofLeave.SelectedItem.Text == "Optional")
                {
                    optinalDates.Visible = true;
                    Selecteddates.Visible = false;
                }
                else
                {
                    dateTimeStartDate.ClearSelection();
                    txtDuration.Value = string.Empty;
                    lblDuration.InnerText = string.Empty;
                    dateTimeStartDate.Focus();

                    optinalDates.Visible = false;
                    Selecteddates.Visible = true;
                }
                return;

            }
            if (!ValidateDate(leaveEDate, "MM/dd/yyyy"))
            {
                lblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                lblError.Text += "<br/>";
                if (ddlTypeofLeave.SelectedItem.Text == "Optional")
                {
                    optinalDates.Visible = true;
                    Selecteddates.Visible = false;
                }
                else
                {
                    dateTimeEndDate.ClearSelection();
                    txtDuration.Value = string.Empty;
                    lblDuration.InnerText = string.Empty;
                    optinalDates.Visible = false;
                    Selecteddates.Visible = true;
                    dateTimeEndDate.Focus();
                }
                return;

            }
            try
            {
                SetDate();
                if (DateTime.Parse(leaveSDate) >= DateTime.Parse(hdnFnclStarts.Value) && DateTime.Parse(leaveEDate) <= DateTime.Parse(hdnFnclEnds.Value))
                {

                    lblError.Text = string.Empty;

                    if (txtDuration.Value != "0" && txtDuration.Value != "")
                    {
                        if (decimal.Parse(txtDuration.Value) > 0)
                        {
                            using (var site = new SPSite(SPContext.Current.Site.Url))
                            {
                                using (var web = site.OpenWeb())
                                {
                                    SPUser user = web.CurrentUser;
                                    hdnCurrentUsername.Value = user.Name;
                                    var list = web.Lists.TryGetList(Utilities.LeaveRequest);
                                    web.AllowUnsafeUpdates = true;

                                    SPListItemCollection leaveDetails = GetListItemCollection(
                                        web.Lists[Utilities.EmployeeLeaves], "Employee ID", lblEmpID.Text,
                                        "Leave Type",
                                        ddlTypeofLeave.SelectedValue, "Year", hdnCurrentYear.Value);
                                    if (leaveDetails.Count != 0)
                                    {
                                        foreach (SPListItem leaveDetail in leaveDetails)
                                        {
                                            if (decimal.Parse(leaveDetail["Leave Balance"].ToString()) <
                                                decimal.Parse(txtDuration.Value) &&
                                                ddlTypeofLeave.SelectedItem.Text != "LOP")
                                            {
                                                lblError.Text = "You dont have enough leave balance in this leave type";
                                                SetDate();
                                            }
                                            else
                                            {

                                                SPListItem newItem = list.Items.Add();

                                                // var itemCollection = empitem.Items;
                                                var entity = new PickerEntity
                                                                 {
                                                                     DisplayText =
                                                                         new SPFieldUserValue(web, hdnReportingTo.Value)
                                                                         .
                                                                         User.
                                                                         LoginName
                                                                 };

                                                //   empitem[Utilities.Manager] =

                                                newItem["RequestedFrom"] = web.AllUsers[web.CurrentUser.LoginName];
                                                newItem["RequestedTo"] = web.AllUsers[entity.DisplayText];
                                                newItem["Leave Type"] = ddlTypeofLeave.SelectedValue;
                                                newItem["Purpose of Leave"] = txtPurpose.Text;
                                                newItem["EmpID"] = lblEmpID.Text;
                                                newItem["Desgination"] = lblDesgination.Text;
                                                newItem["Department"] = lblDepartment.Text;
                                                newItem["Leave Days"] = txtDuration.Value;
                                                newItem["Year"] = hdnCurrentYear.Value;
                                                //if (ddlTypeofLeave.SelectedItem.Text != "Optional")
                                                //{
                                                newItem["Starting Date"] = DateTime.Parse(leaveSDate);
                                                newItem["Ending Date"] = DateTime.Parse(leaveEDate);
                                                newItem["Employee Status"] = "Active";

                                                //dateTimeEndDate.SelectedDate;
                                                //}
                                                //else
                                                //{
                                                //    newItem["Starting Date"] =
                                                //        DateTime.Parse(lstboxOptionalLeaves.SelectedValue);
                                                //    newItem["Ending Date"] =
                                                //        DateTime.Parse(lstboxOptionalLeaves.SelectedValue);
                                                //}
                                                newItem.Update();

                                                decimal leavesBal =
                                                    decimal.Parse(leaveDetail["Leave Balance"].ToString()) -
                                                    decimal.Parse(txtDuration.Value);
                                                if (ddlTypeofLeave.SelectedItem.Text == "LOP")
                                                {
                                                    leaveDetail["Leave Balance"] = 0;
                                                }
                                                else
                                                {
                                                    if (leavesBal % 1 == 0)
                                                    {
                                                        int noOfleaves = Convert.ToInt16(leavesBal);
                                                        leaveDetail["Leave Balance"] = noOfleaves;
                                                    }
                                                    else
                                                    {
                                                        leaveDetail["Leave Balance"] = leavesBal;
                                                    }
                                                }

                                                decimal leavesReq =
                                                    decimal.Parse(leaveDetail["Leave Requested"].ToString()) +
                                                    decimal.Parse(txtDuration.Value);
                                                if (leavesReq % 1 == 0)
                                                {
                                                    int noOfleaves = Convert.ToInt16(leavesReq);
                                                    leaveDetail["Leave Requested"] = noOfleaves;
                                                }
                                                else
                                                {
                                                    leaveDetail["Leave Requested"] = leavesReq;
                                                }

                                                //leaveDetail["Leave Requested"] =
                                                //    decimal.Parse(leaveDetail["Leave Requested"].ToString()) +
                                                //    decimal.Parse(txtDuration.Value);
                                                leaveDetail.Update();

                                                //grvBalanceLeave.DataSource = GetBalanceLeave(lblEmpID.Text);
                                                //grvBalanceLeave.DataBind();
                                                ddlTypeofLeave.ClearSelection();
                                                Response.Redirect(site.Url);

                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            lblError.Text = "Select Valid dates";
                        }
                    }
                    else
                    {
                        lblError.Text = "Select Valid dates";
                    }
                }
                else
                {
                    lblError.Text = "You can't able to select previous/future financial year dates";

                }
                //if (SPContext.Current != null)
                //using (var site = new SPSite(SPContext.Current.Site.Url))
                //{
                //    using (var web = site.OpenWeb())
                //    {
                //        var list = web.Lists.TryGetList(Utilities.LeaveRequest);
                //        web.AllowUnsafeUpdates = true;
                //        SPListItem newItem = list.Items.Add();

                //       // var itemCollection = empitem.Items;

                //            newItem["Leave Type"] = ddlTypeofLeave.SelectedValue;
                //            newItem["Leave Type"] = ddlReportingTo.SelectedValue;
                //            newItem["EmpId"] = lblEmpID.Text;
                //            newItem["Desgination"] = lblDesgination.Text;
                //            newItem["Department"] = lblDepartment.Text;
                //            newItem["Starting Date"] = dateTimeStartDate.SelectedDate;
                //            newItem["Ending Date"] = dateTimeEndDate.SelectedDate;
                //            newItem.Update();

                //        web.AllowUnsafeUpdates = false;
                //    }
                //}
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
예제 #55
0
        private SPUser UpdateMSAScheduleControls(SPWeb oSPWeb)
        {
            SPUser auditedBy = null;

            try
            {
                string spListNameMS = "MSASchedule";

                // Fetch the List
                SPList spListMS = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, spListNameMS));

                if (spListMS != null && !String.IsNullOrEmpty(this.hdnScheduleId.Value))
                {
                    int sid = Convert.ToInt32(this.hdnScheduleId.Value);

                    SPListItem spListItemMS = spListMS.GetItemById(sid);

                    if (spListItemMS["Title"] != null)
                    {
                        string designation = Convert.ToString(spListItemMS["Title"]);

                        if (!String.IsNullOrEmpty(designation))
                        {
                            this.designation_tf.Value = designation;
                            this.designation_tf.Disabled = true;
                        }
                    }

                    if (spListItemMS["Area"] != null)
                    {
                        string areaAudited = Convert.ToString(spListItemMS["Area"]);

                        if (!String.IsNullOrEmpty(areaAudited))
                        {
                            if (areaAudited.Contains("#"))
                            {
                                var temp = areaAudited.Split('#');

                                if (temp != null && temp.Length > 1)
                                {
                                    this.areaAudited_ddl.SelectedValue = temp[1];

                                    if (this.areaAudited_ddl.SelectedIndex > 0)
                                    {
                                        this.areaAudited_ddl.Enabled = false;
                                    }
                                }
                            }
                        }
                    }

                    if (spListItemMS["FFLScheduleName"] != null)
                    {
                        string auditedByUsername = Convert.ToString(spListItemMS["FFLScheduleName"]);

                        if (!String.IsNullOrEmpty(auditedByUsername))
                        {
                            var temp = auditedByUsername.Split('#');

                            if (temp.Length > 1)
                            {
                                temp = temp[0].Split(';');

                                if (temp.Length > 1)
                                {
                                    auditedBy = Utility.GetUser(oSPWeb, null, null, Int32.Parse(temp[0]));
                                }
                            }
                        }

                        if (auditedBy != null)
                        {
                            // Clear existing users from control
                            this.auditedBy_PeopleEditor.Entities.Clear();

                            // PickerEntity object is used by People Picker Control
                            PickerEntity UserEntity = new PickerEntity();

                            // CurrentUser is SPUser object
                            UserEntity.DisplayText = auditedBy.Name;
                            UserEntity.Key = auditedBy.LoginName;

                            // Add PickerEntity to People Picker control
                            this.auditedBy_PeopleEditor.Entities.Add(this.auditedBy_PeopleEditor.ValidateEntity(UserEntity));
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSAForm->UpdateMSAScheduleControls)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);

                message_div.InnerHtml = "Something went wrong!!! Please Contact the administrator.";
                DisableControls();
            }
            return auditedBy;
        }
        void cdcatalog_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                bool isHidden = false;
                PeopleEditor peSpecificUsesGroup = e.Item.FindControl("peSpecificUsesGroup") as PeopleEditor;
                TextBox txtDueDate = e.Item.FindControl("txtDueDate") as TextBox;
                TextBox txtDuration = e.Item.FindControl("txtDuration") as TextBox;
                EncodedLiteral level = e.Item.FindControl("targetAppAdminDescription") as EncodedLiteral;
                InputFormTextBox rtfMessage = e.Item.FindControl("rtfMessage") as InputFormTextBox;
                TextBox txtMessageTitle = e.Item.FindControl("txtMessageTitle")  as TextBox;
                TextBox txtMessage = e.Item.FindControl("txtMessage")  as TextBox;
                var trEmailMessage = e.Item.FindControl("trEmailMessage");
                rtfMessage.Text = "This is text message";
                IModel.ApprovalWFApprover data = e.Item.DataItem as IModel.ApprovalWFApprover;

                if (data.EnableEmail)
                {
                    var template = data.EmailTemplate;
                    var templateItem =EmailTemplateService.GetTemplateByName(template.Url, template.Name);
                    if(templateItem!= null){
                        rtfMessage.Text = templateItem.Body;
                        txtMessageTitle.Text = templateItem.Subject;
                    }
                }

                trEmailMessage.Visible = data.AllowChangeMessage;
                txtMessage.Text = data.TaskInstruction;

                level.Text = data.ApprovalLevelName;
                if (data.DurationPerTask != 0)
                {
                    txtDuration.Text = data.DurationPerTask.ToString();
                    txtDuration.Enabled = false;
                }

                txtDueDate.Text = data.DueDate;

                DateTime dueDate = GetDueDate(data.DueDate);

                if(DateTime.Compare(dueDate, DateTime.MinValue) != 0)
                {
                    txtDueDate.Text = dueDate.ToShortDateString();
                    txtDueDate.Enabled = false;
                }

                if (!String.IsNullOrEmpty(data.ColumnName))
                {
                    try
                    {
                        string approver = this.workflowListItem[new Guid(data.ColumnName)] as string;

                        if (!string.IsNullOrEmpty(approver))
                        {
                            if (this.workflowListItem[new Guid(data.ColumnName)].GetType().Name == Constants.ASSIGMENT_FIELD_NAME)
                            {
                                var names = approver.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                                List<string> loginAccounts = new List<string>();

                                if (names.Length > 1)
                                {
                                    for (int i = 0; i < names.Length; i = i + 2)
                                    {
                                        SPUser user = this.Web.AllUsers.GetByID(int.Parse(names[i]));
                                        loginAccounts.Add(user.LoginName);
                                    }

                                    BindPeoplePicker(peSpecificUsesGroup, loginAccounts);
                                    isHidden = true;
                                }
                            }
                            else
                            {
                                var field = this.workflowListItem.Fields[new Guid(data.ColumnName)];

                                SPFieldUserValueCollection members = this.workflowListItem[new Guid(data.ColumnName)] == null ?
                                                                        null : new SPFieldUserValueCollection(workflowListItem.Web, this.workflowListItem[new Guid(data.ColumnName)].ToString());

                                if (members != null)
                                {
                                    ArrayList entityArrayList = new ArrayList();
                                    for (int i = 0; i < members.Count; i++)
                                    {
                                        PickerEntity entity = new PickerEntity();
                                        if (members[i].User != null)
                                        {
                                            entity.Key = members[i].User.LoginName;
                                        }
                                        else
                                        {

                                            entity.Key = members[i].LookupValue;

                                        }
                                        entityArrayList.Add(entity);
                                    }

                                    peSpecificUsesGroup.UpdateEntities(entityArrayList);
                                    //isHidden = true;
                                }
                            }
                        }
                    }
                    catch (Exception ex) { }
                }

                if (data != null && data.SpecificUserGroup.Count > 0)
                {
                    if(!data.EnableChangeApprovers) peSpecificUsesGroup.Enabled = false;
                    BindPeoplePicker(peSpecificUsesGroup, data.SpecificUserGroup);
                    //isHidden = true;
                }

                if (data != null && data.ManagerApprove)
                {
                    try
                    {
                        if (!data.EnableChangeApprovers) peSpecificUsesGroup.Enabled = false;

                        List<string> loginAccounts = new List<string>();
                        //loginAccounts.Add(IOfficeContext.Manager.LoginName);

                        BindPeoplePicker(peSpecificUsesGroup, loginAccounts);
                    }
                    catch (Exception ex) {
                        SPUtility.TransferToErrorPage(SPHttpUtility.UrlKeyValueDecode("Cannot find the manager of " + SPContext.Current.Web.CurrentUser.Name));
                    }
                }

                if (isHidden)
                {
                    peSpecificUsesGroup.Enabled = false;
                }

            }
        }
예제 #57
0
        private bool InitializeMSAControls(int msaId)
        {
            try
            {
                using (SPSite oSPsite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        string listName = "MSA";
                        // Fetch the List
                        SPList splistMSA = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName));

                        if (splistMSA != null)
                        {
                            SPListItem spListItemMSA = splistMSA.GetItemById(msaId);

                            if (spListItemMSA != null)
                            {
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["AuditedBy"])))
                                {
                                    bool isAllowed = true;

                                    string username = Convert.ToString(spListItemMSA["AuditedBy"]);

                                    SPUser auditedBy = Utility.GetUser(oSPWeb, username);

                                    if (auditedBy != null)
                                    {
                                        // Clear existing users from control
                                        this.auditedBy_PeopleEditor.Entities.Clear();

                                        // PickerEntity object is used by People Picker Control
                                        PickerEntity UserEntity = new PickerEntity();

                                        // CurrentUser is SPUser object
                                        UserEntity.DisplayText = auditedBy.Name;
                                        UserEntity.Key = auditedBy.LoginName;

                                        // Add PickerEntity to People Picker control
                                        this.auditedBy_PeopleEditor.Entities.Add(this.auditedBy_PeopleEditor.ValidateEntity(UserEntity));
                                    }

                                    SPUser CurrentUser = oSPWeb.CurrentUser;
                                    if (CurrentUser != null)
                                    {
                                        if (!Utility.CompareUsername(username, CurrentUser.LoginName))
                                        {
                                            isAllowed = false;
                                        }
                                    }

                                    if (isAllowed == false)
                                    {
                                        if (CheckPermission())
                                        {
                                            DisableControls();
                                        }
                                        else
                                        {
                                            string accessDeniedUrl = Utility.GetRedirectUrl("Access_Denied");

                                            if (!String.IsNullOrEmpty(accessDeniedUrl))
                                            {
                                                DisableControls();
                                                Page.Response.Redirect(accessDeniedUrl, false);
                                            }
                                            return false;
                                        }
                                    }
                                }

                                bool isSavedAsDraft = true;

                                if (spListItemMSA["IsSavedAsDraft"] != null)
                                {
                                    isSavedAsDraft = Convert.ToBoolean(spListItemMSA["IsSavedAsDraft"]);

                                    if (isSavedAsDraft == false)
                                    {
                                        this.message_div.InnerHtml = "Update operation is not allowed on saved records!!! Please Contact the administrator.";
                                        DisableControls();
                                    }
                                }

                                if (isSavedAsDraft == false && spListItemMSA["MSADate"] != null && !String.IsNullOrEmpty(Convert.ToString(spListItemMSA["MSADate"])))
                                {
                                    DateTime date;
                                    bool bValid = DateTime.TryParse(Convert.ToString(spListItemMSA["MSADate"]), new CultureInfo("en-GB"), DateTimeStyles.AssumeLocal, out date);

                                    if (bValid)
                                    {
                                        this.msaDate_dtc.SelectedDate = date.Date;
                                    }
                                    else
                                    {
                                        this.msaDate_dtc.SelectedDate = Convert.ToDateTime(spListItemMSA["MSADate"]).Date;
                                    }
                                }

                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["AccompaniedBy"])))
                                {
                                    this.accompaniedBy_tf.Value = Convert.ToString(spListItemMSA["AccompaniedBy"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["Designation"])))
                                {
                                    this.designation_tf.Value = Convert.ToString(spListItemMSA["Designation"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["AreaAudited"])))
                                {
                                    this.areaAudited_ddl.SelectedValue = Convert.ToString(spListItemMSA["AreaAudited"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["StartTime"])))
                                {
                                    DateTime startTime = Convert.ToDateTime(spListItemMSA["StartTime"]);
                                    this.startTime_dtc.SelectedDate = startTime;
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["EndTime"])))
                                {
                                    DateTime endTime = Convert.ToDateTime(spListItemMSA["EndTime"]);
                                    this.endTime_dtc.SelectedDate = endTime;
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["NoOfUnsafeActs"])))
                                {
                                    this.noOfUnsafeActs_tf.InnerHtml = Convert.ToString(spListItemMSA["NoOfUnsafeActs"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["NoOfUnsafeConditions"])))
                                {
                                    this.noOfUnsafeConditions_tf.InnerHtml = Convert.ToString(spListItemMSA["NoOfUnsafeConditions"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["NoOfSeriousInjury"])))
                                {
                                    this.noOfSeriousInjury_tf.InnerHtml = Convert.ToString(spListItemMSA["NoOfSeriousInjury"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["NoOfFatalityInjury"])))
                                {
                                    this.noOfFatalityInjury_tf.InnerHtml = Convert.ToString(spListItemMSA["NoOfFatalityInjury"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["PositivePoints"])))
                                {
                                    this.hdnPositivePointList.Value = Convert.ToString(spListItemMSA["PositivePoints"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["AreaOfImprovement"])))
                                {
                                    this.hdnAreaOfImprovementList.Value = Convert.ToString(spListItemMSA["AreaOfImprovement"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["MSAQualityScore"])))
                                {
                                    this.msaQualityScore_tf.InnerText = Convert.ToString(spListItemMSA["MSAQualityScore"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSA["ScheduleId"])))
                                {
                                    this.hdnScheduleId.Value = Convert.ToString(spListItemMSA["ScheduleId"]);
                                }

                                foreach (String attachmentname in spListItemMSA.Attachments)
                                {
                                    String attachmentAbsoluteURL =
                                    spListItemMSA.Attachments.UrlPrefix // gets the containing directory URL
                                    + attachmentname;
                                    // To get the SPSile reference to the attachment just use this code
                                    SPFile attachmentFile = oSPWeb.GetFile(attachmentAbsoluteURL);

                                    StringBuilder sb = new StringBuilder();

                                    HtmlTableRow tRow = new HtmlTableRow();

                                    HtmlTableCell removeLink = new HtmlTableCell();
                                    HtmlTableCell fileLink = new HtmlTableCell();

                                    sb.Append(String.Format("<a href='{0}/{1}' target='_blank'>{2}</a>", oSPWeb.Url, attachmentFile.Url, attachmentname));
                                    removeLink.InnerHtml = "<span class='btn-danger removeLink' style='padding:3px; margin-right:3px; border-radius:2px;'><i class='glyphicon glyphicon-remove'></i></span><span class='fileName' style='display:none;'>" + attachmentFile.Name + "</span>";

                                    fileLink.InnerHtml = sb.ToString();

                                    tRow.Cells.Add(removeLink);
                                    tRow.Cells.Add(fileLink);

                                    this.grdAttachments.Rows.Add(tRow);
                                }


                                string p1 = "~|~"; //separate records
                                string p2 = "*|*"; //separate content with in a record

                                //Positive Point List
                                List<string> lstPositivePoint = Utility.GetFormattedDataList(this.hdnPositivePointList.Value, p1, true);

                                //Area Of Improvement List
                                List<string> lstAreaOfImprovement = Utility.GetFormattedDataList(this.hdnAreaOfImprovementList.Value, p1, true);


                                if (lstPositivePoint != null)
                                {
                                    FillPositivePointGrid(lstPositivePoint);
                                }

                                if (lstAreaOfImprovement != null)
                                {
                                    FillAreaOfImprovementGrid(lstAreaOfImprovement);
                                }

                                //Contacts
                                List<MSAContact> lstMSAContact = GetFormattedContactsByMSA(oSPWeb, msaId);

                                //Recommendations
                                List<MSARecommendation> lstMSARecommendation = GetFormattedRecommendationsByMSA(oSPWeb, msaId);

                                StringBuilder ids = new StringBuilder();

                                if (lstMSAContact != null && lstMSARecommendation != null)
                                {
                                    //Add contacts in grid
                                    foreach (var contact in lstMSAContact)
                                    {
                                        HtmlTableRow tRow = new HtmlTableRow();

                                        tRow.Attributes.Add("class", "contactItem");

                                        tRow.Cells.Add(new HtmlTableCell() { InnerHtml = Convert.ToString(this.contactDetails_table.Rows.Count) });

                                        HtmlTableCell contactId = new HtmlTableCell();
                                        HtmlTableCell contactDetail = new HtmlTableCell();

                                        string actions = "<span class='btn btn-default editContact'><i class='glyphicon glyphicon-pencil'></i></span><span class='btn btn-danger removeContact'><i class='glyphicon glyphicon-remove'></i></span>";

                                        contactId.InnerHtml = "<span class='contactId'>" + Convert.ToString(contact.ContactId) + "</span>";
                                        contactId.Attributes.Add("style", "display:none");

                                        contactDetail.InnerHtml = "<span class='contactDetail'>" + Convert.ToString(contact.ContactDetail) + "</span>";

                                        tRow.Cells.Add(contactId);
                                        tRow.Cells.Add(contactDetail);

                                        tRow.Cells.Add(new HtmlTableCell() { InnerHtml = actions });

                                        this.contactDetails_table.Rows.Add(tRow);

                                        ids.Append(Convert.ToString(contact.ContactId));
                                        ids.Append(p2);
                                    }

                                    ids.Append(p1);


                                    //Add recommendations in grid
                                    foreach (var recommendation in lstMSARecommendation)
                                    {
                                        HtmlTableRow tRow = new HtmlTableRow();

                                        tRow.Attributes.Add("class", "recommendationItem");

                                        tRow.Cells.Add(new HtmlTableCell() { InnerHtml = Convert.ToString(this.recommendationDetails_table.Rows.Count) });

                                        HtmlTableCell recommendationId = new HtmlTableCell();
                                        HtmlTableCell recommendationNo = new HtmlTableCell();
                                        HtmlTableCell description = new HtmlTableCell();
                                        HtmlTableCell typeOfVoilation = new HtmlTableCell();
                                        HtmlTableCell responsiblePersonUsername = new HtmlTableCell();
                                        HtmlTableCell responsiblePersonEmail = new HtmlTableCell();
                                        HtmlTableCell responsibleSection = new HtmlTableCell();
                                        HtmlTableCell responsibleSectionId = new HtmlTableCell();
                                        HtmlTableCell responsibleDepartment = new HtmlTableCell();
                                        HtmlTableCell injuryClassification = new HtmlTableCell();
                                        HtmlTableCell responsibleDepartmentId = new HtmlTableCell();
                                        HtmlTableCell consentTaken = new HtmlTableCell();
                                        HtmlTableCell targetDate = new HtmlTableCell();
                                        HtmlTableCell observationCategory = new HtmlTableCell();
                                        HtmlTableCell observationSubCategory = new HtmlTableCell();
                                        HtmlTableCell observationSpot = new HtmlTableCell();
                                        HtmlTableCell status = new HtmlTableCell();

                                        string actions = "<span class='btn btn-default editRecommendation' ><i class='glyphicon glyphicon-pencil'></i></span><span class='btn btn-danger removeRecommendation'><i class='glyphicon glyphicon-remove'></i></span>";

                                        recommendationId.InnerHtml = "<span class='recommendationId'>" + Convert.ToString(recommendation.RecommendationId) + "</span>";
                                        recommendationId.Attributes.Add("style", "display:none");

                                        recommendationNo.InnerHtml = "<span class='recommendationNo'>" + Convert.ToString(recommendation.RecommendationNo) + "</span>";
                                        recommendationNo.Attributes.Add("style", "display:none");

                                        description.Attributes.Add("class", "td-description");
                                        description.InnerHtml = "<span class='description'>" + Convert.ToString(recommendation.Description) + "</span>";
                                        typeOfVoilation.InnerHtml = "<span class='typeOfVoilation'>" + Convert.ToString(recommendation.TypeOfVoilation) + "</span>";
                                        responsiblePersonUsername.InnerHtml = "<span class='username'>" + Convert.ToString(recommendation.RPUsername) + "</span>";

                                        responsiblePersonEmail.InnerHtml = "<span class='email'>" + Convert.ToString(recommendation.RPEmail) + "</span>";
                                        responsiblePersonEmail.Attributes.Add("style", "display:none");

                                        responsibleSection.InnerHtml = "<span class='sectionName'>" + Convert.ToString(recommendation.SectionName) + "</span>";

                                        responsibleSectionId.InnerHtml = "<span class='sectionId'>" + Convert.ToString(recommendation.SectionId) + "</span>";
                                        responsibleSectionId.Attributes.Add("style", "display:none");

                                        responsibleDepartment.InnerHtml = "<span class='departmentName'>" + Convert.ToString(recommendation.DepartmentName) + "</span>";
                                        injuryClassification.InnerHtml = "<span class='injuryClass'>" + Convert.ToString(recommendation.InjuryClass) + "</span>";

                                        responsibleDepartmentId.InnerHtml = "<span class='departmentId'>" + Convert.ToString(recommendation.DepartmentId) + "</span>";
                                        responsibleDepartmentId.Attributes.Add("style", "display:none");

                                        consentTaken.InnerHtml = "<span class='consentTaken'>" + ((recommendation.ConsentTaken == true) ? "Yes" : "No") + "</span>";
                                        targetDate.InnerHtml = "<span class='targetDate'>" + Convert.ToString(recommendation.TargetDate) + "</span>";
                                        observationCategory.InnerHtml = "<span class='category'>" + Convert.ToString(recommendation.ObservationCategory) + "</span>";

                                        observationSubCategory.InnerHtml = "<span class='subCategory'>" + Convert.ToString(recommendation.ObservationSubcategory) + "</span>";
                                        //observationSubCategory.Attributes.Add("style", "display:none");

                                        observationSpot.InnerHtml = "<span class='observationSpot'>" + ((recommendation.ObservationSpot == true) ? "Yes" : "No") + "</span>";
                                        status.InnerHtml = "<span class='status'>" + Convert.ToString(recommendation.Status) + "</span>";

                                        tRow.Cells.Add(recommendationId);
                                        tRow.Cells.Add(description);
                                        tRow.Cells.Add(typeOfVoilation);
                                        tRow.Cells.Add(responsiblePersonUsername);
                                        tRow.Cells.Add(responsibleSection);
                                        tRow.Cells.Add(responsibleSectionId);
                                        tRow.Cells.Add(responsibleDepartment);
                                        tRow.Cells.Add(injuryClassification);
                                        tRow.Cells.Add(responsibleDepartmentId);
                                        tRow.Cells.Add(consentTaken);
                                        tRow.Cells.Add(targetDate);
                                        tRow.Cells.Add(observationCategory);
                                        tRow.Cells.Add(observationSubCategory);
                                        tRow.Cells.Add(observationSpot);
                                        tRow.Cells.Add(status);

                                        tRow.Cells.Add(new HtmlTableCell() { InnerHtml = actions });

                                        this.recommendationDetails_table.Rows.Add(tRow);

                                        ids.Append(Convert.ToString(recommendation.RecommendationId));
                                        ids.Append(p2);
                                    }

                                    this.hdnIdList.Value = ids.ToString();
                                }
                            }
                        }
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSAForm->InitializeMSAControls)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);

                message_div.InnerHtml = "Something went wrong!!! Please Contact the administrator.";
                DisableControls();
            }

            return false;
        }
        private bool InitializeMSARecommendationControls(int recommendationId)
        {
            try
            {
                using (SPSite oSPsite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        string listName = "MSARecommendation";
                        // Fetch the List
                        SPList spListMSAR = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName));

                        if (spListMSAR != null)
                        {
                            SPListItem spListItemMSAR = spListMSAR.GetItemById(recommendationId);

                            if (spListItemMSAR != null)
                            {
                                bool isAllowed = true;
                                bool isCompleted = false;
                                SPUser responsiblePerson = null;

                                //Check Permissions
                                if (spListItemMSAR["Assignee"] != null)
                                {
                                    string assignee = Convert.ToString(spListItemMSAR["Assignee"]);
                                    SPUser currentUser = oSPWeb.CurrentUser;

                                    if (currentUser != null && !Utility.CompareUsername(currentUser.LoginName, assignee))
                                    {
                                        isAllowed = false;
                                    }

                                    if (isAllowed == false)
                                    {
                                        if (CheckPermission())
                                        {
                                            DisableControls();
                                        }
                                        else
                                        {
                                            string accessDeniedUrl = Utility.GetRedirectUrl("Access_Denied");

                                            if (!String.IsNullOrEmpty(accessDeniedUrl))
                                            {
                                                DisableControls();
                                                Page.Response.Redirect(accessDeniedUrl, false);
                                            }
                                            return false;
                                        }
                                    }

                                }

                                if (spListItemMSAR["Status"] != null)
                                {
                                    string status = Convert.ToString(spListItemMSAR["Status"]);

                                    if (status.Equals("Completed", StringComparison.OrdinalIgnoreCase))
                                    {
                                        isCompleted = true;
                                        this.approvedBy_div.Visible = true;
                                        DisableControls();
                                    }
                                }

                                if (spListItemMSAR["TargetDate"] != null)
                                {
                                    DateTime targetDate;
                                    bool bValid = DateTime.TryParse(Convert.ToString(spListItemMSAR["TargetDate"]), new CultureInfo("en-GB"), DateTimeStyles.AssumeLocal, out targetDate);

                                    if (!bValid)
                                    {
                                        targetDate = Convert.ToDateTime(spListItemMSAR["TargetDate"]);
                                    }

                                    this.targetDate_tf.Value = targetDate.ToShortDateString();
                                }

                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["RecommendationNo"])))
                                {
                                    this.recommendationNo_tf.Value = Convert.ToString(spListItemMSAR["RecommendationNo"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["Status"])))
                                {
                                    this.status_ddl.Value = Convert.ToString(spListItemMSAR["Status"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["MSARecommendationDescription"])))
                                {
                                    this.description_ta.Value = Convert.ToString(spListItemMSAR["MSARecommendationDescription"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ResponsibleDepartment"])))
                                {
                                    this.responsibleDepartment_tf.Value = Convert.ToString(spListItemMSAR["ResponsibleDepartment"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ResponsibleSection"])))
                                {
                                    this.responsibleSection_tf.Value = Convert.ToString(spListItemMSAR["ResponsibleSection"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["InjuryClass"])))
                                {
                                    this.injuryClassification_tf.Value = Convert.ToString(spListItemMSAR["InjuryClass"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["TypeOfVoilation"])))
                                {
                                    this.typeOfVoilation_tf.Value = Convert.ToString(spListItemMSAR["TypeOfVoilation"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ObservationCategory"])))
                                {
                                    this.observationCategoryA_tf.Value = Convert.ToString(spListItemMSAR["ObservationCategory"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ObservationCategory"])))
                                {
                                    this.observationCategoryA_tf.Value = Convert.ToString(spListItemMSAR["ObservationCategory"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["LastStatement"])))
                                {
                                    this.lastStatement_ta.Value = Convert.ToString(spListItemMSAR["LastStatement"]);
                                }
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ClosureJustification"])))
                                {
                                    string guessMePattern = "*|~^|^~|*";

                                    string justifications = Convert.ToString(spListItemMSAR["ClosureJustification"]);
                                    this.history_div.InnerHtml = Utility.GetFormattedData(justifications, guessMePattern, true);
                                }
                                else
                                {
                                    this.history_div.InnerHtml = "<p class='dataItem'>There is no history available.</p>";
                                }

                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ApprovedBy"])))
                                {
                                    this.approvedBy_tf.Value = Convert.ToString(spListItemMSAR["ApprovedBy"]);
                                }

                                foreach (String attachmentname in spListItemMSAR.Attachments)
                                {
                                    String attachmentAbsoluteURL =
                                    spListItemMSAR.Attachments.UrlPrefix // gets the containing directory URL
                                    + attachmentname;
                                    // To get the SPSile reference to the attachment just use this code
                                    SPFile attachmentFile = oSPWeb.GetFile(attachmentAbsoluteURL);

                                    StringBuilder sb = new StringBuilder();

                                    HtmlTableRow tRow = new HtmlTableRow();

                                    HtmlTableCell removeLink = new HtmlTableCell();
                                    HtmlTableCell fileLink = new HtmlTableCell();

                                    sb.Append(String.Format("<a href='{0}/{1}' target='_blank'>{2}</a>", oSPWeb.Url, attachmentFile.Url, attachmentname));
                                    removeLink.InnerHtml = "<span class='btn-danger removeLink' style='padding:3px; margin-right:3px; border-radius:2px;'><i class='glyphicon glyphicon-remove'></i></span><span class='fileName' style='display:none;'>" + attachmentFile.Name + "</span>";

                                    fileLink.InnerHtml = sb.ToString();

                                    tRow.Cells.Add(removeLink);
                                    tRow.Cells.Add(fileLink);

                                    this.grdAttachments.Rows.Add(tRow);
                                }

                                //Responsible Person
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ResponsiblePerson"])))
                                {
                                    string username = Convert.ToString(spListItemMSAR["ResponsiblePerson"]);

                                    responsiblePerson = Utility.GetUser(oSPWeb, username);

                                    if (responsiblePerson == null)
                                    {
                                        if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["Assignee"])))
                                        {
                                            string tempUsername = Convert.ToString(spListItemMSAR["Assignee"]);
                                            responsiblePerson = Utility.GetUser(oSPWeb, tempUsername);
                                        }
                                    }
                                    if (responsiblePerson != null)
                                    {
                                        // Clear existing users from control
                                        this.responsiblePerson_PeopleEditor.Entities.Clear();

                                        // PickerEntity object is used by People Picker Control
                                        PickerEntity UserEntity = new PickerEntity();

                                        // CurrentUser is SPUser object
                                        UserEntity.DisplayText = responsiblePerson.Name;
                                        UserEntity.Key = responsiblePerson.LoginName;

                                        // Add PickerEntity to People Picker control
                                        this.responsiblePerson_PeopleEditor.Entities.Add(this.responsiblePerson_PeopleEditor.ValidateEntity(UserEntity));
                                    }
                                }


                                //Status
                                if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["Status"])))
                                {
                                    //Write some code here
                                }

                                //ResponsibleSection
                                if (spListItemMSAR["ResponsibleSection"] != null)
                                {
                                    int sectionId = Convert.ToInt32(spListItemMSAR["ResponsibleSection"]);

                                    listName = "Section";
                                    // Fetch the List
                                    SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName));

                                    if (spList != null && sectionId > 0)
                                    {
                                        SPListItem spListItem = spList.GetItemById(sectionId);

                                        if (spListItem != null)
                                        {
                                            this.responsibleSection_tf.Value = Convert.ToString(spListItem["Title"]);
                                        }
                                    }
                                }

                                //ResponsibleDepartment
                                if (spListItemMSAR["ResponsibleDepartment"] != null)
                                {
                                    int id = Convert.ToInt32(spListItemMSAR["ResponsibleDepartment"]);

                                    listName = "Department";
                                    // Fetch the List
                                    SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName));

                                    if (spList != null && id > 0)
                                    {
                                        SPListItem spListItem = spList.GetItemById(id);

                                        if (spListItem != null)
                                        {
                                            string departmentName = Convert.ToString(spListItem["Title"]);
                                            this.responsibleDepartment_tf.Value = departmentName;

                                            if (String.IsNullOrEmpty(this.approvedBy_tf.Value))
                                            {
                                                var hodLI = FillApprovalAuthority(oSPWeb, departmentName);

                                                var currentUser = oSPWeb.CurrentUser;

                                                if (currentUser != null && hodLI != null && currentUser.Email.Equals(hodLI.Value, StringComparison.OrdinalIgnoreCase))
                                                {
                                                    this.approvalAuthority_ddl.SelectedValue = hodLI.Value;
                                                    this.approvalAuthority_ddl.Enabled = false;
                                                    this.approvalAuthority_ddl.Attributes.Add("class", "formcontrol disableControl");
                                                }
                                            }
                                            else
                                            {
                                                var user = Utility.GetUser(oSPWeb, null, this.approvedBy_tf.Value);
                                                if (user != null)
                                                {
                                                    this.approvalAuthority_ddl.Items.Add(new ListItem(user.Name, user.Email));

                                                    this.approvalAuthority_ddl.Enabled = false;
                                                    this.approvalAuthority_ddl.Attributes.Add("class", "formcontrol disableControl");

                                                    this.approvedBy_tf.Value = user.Name;

                                                    this.approvalAuthority_ddl.Items.Insert(0, new ListItem("Please Select", "0"));

                                                    this.approvalAuthority_ddl.DataBind();

                                                    this.approvalAuthority_ddl.SelectedValue = user.Email;

                                                }
                                            }
                                        }
                                    }
                                }


                                //Initiated By
                                if (spListItemMSAR["MSAID"] != null)
                                {
                                    int id = Convert.ToInt32(spListItemMSAR["MSAID"]);

                                    //Department
                                    listName = "MSA";
                                    // Fetch the List
                                    SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName));

                                    if (spList != null)
                                    {
                                        SPListItem spListItem = spList.GetItemById(id);

                                        if (spListItem != null)
                                        {
                                            if (!String.IsNullOrEmpty(Convert.ToString(spListItem["AuditedBy"])))
                                            {
                                                string auditedBy = Convert.ToString(spListItem["AuditedBy"]);
                                                var spUser = Utility.GetUser(oSPWeb, auditedBy);
                                                if (spUser != null)
                                                {
                                                    this.initiatedBy_tf.Value = spUser.Name;
                                                }
                                                else
                                                {
                                                    this.initiatedBy_tf.Value = Convert.ToString(spListItem["AuditedBy"]);
                                                }
                                            }
                                        }
                                    }
                                }


                                //Update Control on the basis of current operation

                                SPUser spCurrentUser = oSPWeb.CurrentUser;
                                string approvingAuthorityEmail = null;

                                if (this.approvalAuthority_ddl != null && this.approvalAuthority_ddl.Items.Count > 0)
                                {
                                    approvingAuthorityEmail = this.approvalAuthority_ddl.SelectedValue;
                                }

                                //Case: Responsible Person is also Approving Authority
                                if (isAllowed == true && isCompleted == false && responsiblePerson != null && !String.IsNullOrEmpty(responsiblePerson.Email) && responsiblePerson.Email.Equals(approvingAuthorityEmail, StringComparison.OrdinalIgnoreCase))
                                {
                                    this.btnReject.Visible = false;
                                    this.btnApprove.Visible = true;
                                    this.btnSend.Visible = false;
                                    this.approvedBy_div.Visible = true;
                                    this.approvedBy_tf.Value = responsiblePerson.Name;
                                }
                                else if (isAllowed == true && isCompleted == false && spCurrentUser != null && !String.IsNullOrEmpty(approvingAuthorityEmail))
                                {
                                    if (spCurrentUser.Email.Equals(approvingAuthorityEmail, StringComparison.OrdinalIgnoreCase))
                                    {
                                        this.btnApprove.Visible = true;
                                        this.btnReject.Visible = true;
                                        this.btnSend.Visible = false;
                                        //this.btnSave.Visible = true;
                                        this.approvedBy_div.Visible = true;
                                    }
                                    else
                                    {
                                        this.btnApprove.Visible = false;
                                        this.btnReject.Visible = false;
                                        this.btnSend.Visible = true;
                                        //this.btnSave.Visible = true;
                                        this.approvedBy_div.Visible = false;
                                    }
                                }
                                else
                                {
                                    DisableControls();
                                }



                                bool isSavedAsDraft = Convert.ToBoolean(spListItemMSAR["IsSavedAsDraft"]);

                                if (isSavedAsDraft == true)
                                {
                                    DisableControls();
                                }
                            }
                        }
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSARecommendation->InitializeMSARecommendationControls)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);

                message_div.InnerHtml = "Something went wrong!!! Please Contact the administrator.";
                DisableControls();
            }

            return false;
        }
        protected void BtnRegisterClick(object sender, EventArgs e)
        {
            string dOP = ((TextBox)(DtDOP.Controls[0])).Text;
            string dOJ = ((TextBox)(DtDoj.Controls[0])).Text;
            // string dOB = ((TextBox)(DtDOB.Controls[0])).Text;

            if (SPContext.Current != null)
            {
                if (txtfristname.Text == "")
                {
                    LblError.Text = "All Fields are required field.";
                    LblError.Text += "<br/>";
                    return;
                }
                if (txtlastname.Text == "")
                {
                    LblError.Text = "All Fields are required field.";
                    LblError.Text += "<br/>";
                    return;
                }
                if (txtempid.Text == "")
                {
                    LblError.Text = "All Fields are required field.";
                    LblError.Text += "<br/>";
                    return;
                }
                if (DdlDep.SelectedIndex < 1)
                {
                    LblError.Text = "All Fields are required field.";
                    LblError.Text += "<br/>";
                    return;
                }
                if (DdlDesignation.SelectedIndex < 1)
                {
                    LblError.Text = "All Fields are required field.";
                    LblError.Text += "<br/>";
                    return;
                }

                if (DdlEmptype.SelectedIndex < 1)
                {
                    LblError.Text = "All Fields are required field.";
                    LblError.Text += "<br/>";
                    return;
                }

                //if (!ValidateDate(dOB, "MM/dd/yyyy"))
                //{
                //    LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                //    LblError.Text += "<br/>";
                //    DtDOB.ClearSelection();
                //    DtDOB.Focus();
                //    return;

                //}
                //else if (DateTime.Parse(dOB) > DateTime.Now)
                //{
                //    LblError.Text = "DOB should be Less than or equal to today.";
                //    LblError.Text += "<br/>";
                //    divdop.Visible = true;
                //    DtDOB.ClearSelection();
                //    DtDOB.Focus();
                //    return;
                //}
                if (string.IsNullOrEmpty(dOJ))
                {
                    LblError.Text = "All Fields are required field.";
                    LblError.Text += "<br/>";
               //     divdop.Visible = true;
                    return;
                }
                if (!ValidateDate(dOJ, "MM/dd/yyyy"))
                {
                    LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                    LblError.Text += "<br/>";
                    DtDoj.ClearSelection();
                    DtDoj.Focus();
                    return;

                }
                else if (DateTime.Parse(dOJ) > DateTime.Now)
                {
                    LblError.Text = "DOJ should be Less than or equal to today.";
                    LblError.Text += "<br/>";
                   // divdop.Visible = true;
                    DtDoj.ClearSelection();
                    DtDoj.Focus();
                    return;
                }
                if (DdlEmptype.SelectedItem.Value.Trim() == "Permanent")
                {

                    if (string.IsNullOrEmpty(dOP))
                    {
                        LblError.Text = "All Fields are required field.";
                        LblError.Text += "<br/>";
                        divdop.Visible = true;
                        return;
                    }
                    else if (!ValidateDate(dOP, "MM/dd/yyyy"))
                    {
                        LblError.Text = "Date format should be in 'MM/DD/YYYY' format.";
                        LblError.Text += "<br/>";
                        divdop.Visible = true;
                        DtDOP.ClearSelection();
                        DtDOP.Focus();
                        return;

                    }
                    else if (DateTime.Parse(dOP) > DateTime.Now)
                    {
                        LblError.Text = "DOP should be Less than or equal to today.";
                        LblError.Text += "<br/>";
                        divdop.Visible = true;
                        DtDOP.ClearSelection();
                        DtDOP.Focus();
                        return;
                    }
                    else if (DateTime.Parse(dOP) < DateTime.Parse(dOJ))
                    {
                        LblError.Text = "DOP should be greater than or equal to DOJ.";
                        LblError.Text += "<br/>";
                        return;
                    }
                }

                //if (DateTime.Parse(dOJ) < DateTime.Parse(dOB))
                //{
                //    LblError.Text = "DOJ should be greater than DOB.";
                //    LblError.Text += "<br/>";
                //    return;
                //}
                //else
                //{
                try
                {
                    using (var site = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (var web = site.OpenWeb())
                        {
                            var list = web.Lists.TryGetList(Utilities.EmployeeScreen);
                            web.AllowUnsafeUpdates = true;

                            var newItem = list.Items.Add();
                            var empdupID = txtempid.Text;
                            var query = new SPQuery
                                            {
                                                Query = @"<Where>
                                                            <Eq>
                                                        <FieldRef Name='Title' />
                                                                     <Value Type='Text'>" +
                                                        empdupID + @"</Value>
                                                            </Eq>
                                                     </Where>"
                                            };
                            var collection = list.GetItems(query);
                            if (collection.Count == 0)
                            {
                                newItem[Utilities.EmployeeId] = txtempid.Text;
                                newItem[Utilities.EmployeeName] =
                                    web.AllUsers[peoplepickeremp.Accounts[0].ToString()];
                                newItem[Utilities.FirstName] = txtfristname.Text;
                                newItem[Utilities.LastName] = txtlastname.Text;
                                newItem["Employee Type"] = DdlEmptype.SelectedValue;
                                newItem["Department"] = DdlDep.SelectedValue;
                                newItem["Designation"] = DdlDesignation.SelectedValue;
                                //newItem[Utilities.Email] = Txtmail.Text;
                                //newItem[Utilities.Mobile] = TxtContact.Text;
                                newItem[Utilities.DateofJoin] = DateTime.Parse(GetFormatedDate(dOJ));// DtDoj.SelectedDate;
                                //newItem[Utilities.DOB] = DateTime.Parse(GetFormatedDate(dOB)); //DtDOB.SelectedDate;
                                if (DdlEmptype.SelectedItem.Text.Trim() == "Permanent")
                                {
                                    newItem["Date of Permanent"] = DateTime.Parse(GetFormatedDate(dOP));//DtDOP.SelectedDate;
                                }
                                var entity = new PickerEntity
                                                 {
                                                     DisplayText =
                                                         new SPFieldUserValue(web, ddlReportingTo.SelectedItem.Value)
                                                         .
                                                         User.
                                                         LoginName
                                                 };
                                newItem[Utilities.Manager] = web.AllUsers[entity.DisplayText];
                                newItem.Update();

                                var leavelist = web.Lists.TryGetList(Utilities.LeaveDays);
                                var field = leavelist.Fields["Employee Type"];
                                var leaveDaysQuery = new SPQuery
                                                         {
                                                             Query =
                                                                 @"<Where>
                                                <Eq>
                                                    <FieldRef Name='" +
                                                                 field.InternalName + @"' />
                                                    <Value Type='Lookup'>" +
                                                                 DdlEmptype.SelectedItem.Text + @"</Value>
                                                    </Eq>
                                                     </Where>"
                                                         };
                                var leaveDayscollection = leavelist.GetItems(leaveDaysQuery);

                                foreach (SPListItem leaveType in leaveDayscollection)
                                {
                                    var empLeavelist = web.Lists.TryGetList(Utilities.EmployeeLeaves);
                                    var empLeaveItem = empLeavelist.Items.Add();
                                    var emptype = new SPFieldLookupValue(leaveType["Employee Type"].ToString());
                                    var lveType = new SPFieldLookupValue(leaveType["Leave Type"].ToString());

                                    empLeaveItem["Employee ID"] = txtempid.Text;
                                    empLeaveItem[Utilities.EmployeeName] =
                                        web.AllUsers[peoplepickeremp.Accounts[0].ToString()];
                                    empLeaveItem["Leave Type"] = leaveType["Leave Type"].ToString();

                                    if (lveType.LookupValue == "Comp off")
                                    {
                                        empLeaveItem["Leave Balance"] = 0;
                                    }
                                    else if (lveType.LookupValue == "LOP")
                                    {
                                        empLeaveItem["Leave Balance"] = 0;
                                    }
                                    else if (lveType.LookupValue == "Optional")
                                    {
                                        empLeaveItem["Leave Balance"] =
                                            decimal.Parse(leaveType["Leave Days"].ToString());
                                    }
                                    else
                                    {
                                        if (emptype.LookupValue.Trim() == "Permanent")
                                        {
                                            int dopMonth = DateTime.Parse(GetFormatedDate(dOP)).Month;// DtDOP.SelectedDate.Month;
                                            int monthDiff = GetMonthDifference(dopMonth);
                                            decimal leaves = decimal.Parse(leaveType["Leave Days"].ToString()) *
                                                             monthDiff;
                                            if (leaves % 1 == 0)
                                            {
                                                int noOfleaves = Convert.ToInt16(leaves);
                                                empLeaveItem["Leave Balance"] = noOfleaves;
                                            }
                                            else
                                            {
                                                empLeaveItem["Leave Balance"] = leaves;
                                            }
                                        }
                                        else
                                        {
                                            decimal leaves = decimal.Parse(leaveType["Leave Days"].ToString());
                                            if (leaves % 1 == 0)
                                            {
                                                int noOfleaves = Convert.ToInt16(leaves);
                                                empLeaveItem["Leave Balance"] = noOfleaves;
                                            }
                                            else
                                            {
                                                empLeaveItem["Leave Balance"] = leaves;
                                            }
                                        }
                                    }

                                    empLeaveItem["Leave utilized"] = 0;
                                    empLeaveItem["Leave Requested"] = 0;
                                    empLeaveItem["Reporting Manager"] = web.AllUsers[entity.DisplayText];
                                    empLeaveItem[Utilities.Year] = hdnCurrentYear.Value;
                                    empLeaveItem["Employee Type"] = DdlEmptype.SelectedValue;
                                    empLeaveItem.Update();

                                }

                                Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup(); SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, '1');</script>");

                                //Context.Response.Write("<script type='text/javascript'>window.Location = window.Location;</script>");
                                Context.Response.Flush();
                                Context.Response.End();

                                //Response.Redirect(SPContext.Current.Web.Url);

                                web.AllowUnsafeUpdates = false;
                            }

                            else
                            {
                                LblError.Text = "Employee id is already exists.";
                                LblError.Text += "<br/>";
                            }
                        }
                    }
                }

                catch (Exception ex)
                {
                    LblError.Text = ex.Message;
                }
                // }
            }
        }
        internal DataTable GetEmployeeLeaves()
        {
            DataTable dataTable = EmployeeLeavesStructure();

            try
            {
                SPListItemCollection employeeList;
                SPUser user = SPContext.Current.Web.CurrentUser;

                string currentUser = user.Name;
                if (IsMemberInGroup("Admin"))
                {
                    employeeList = SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeScreen).GetItems();
                }
                else
                {
                    employeeList =
                        GetListItemCollection(SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeScreen),
                                              Utilities.Manager, currentUser);
                }

                foreach (SPListItem employee in employeeList)
                {
                    DataRow dataRow = dataTable.NewRow();

                    dataRow["Employee Id"] = employee["Employee ID"].ToString();
                    var entity = new PickerEntity
                                     {
                                         DisplayText =
                                             new SPFieldUserValue(SPContext.Current.Web,
                                                                  employee["Employee Name"].ToString()).User.
                                             Name
                                     };
                    var entityRep = new PickerEntity
                                        {
                                            DisplayText =
                                                new SPFieldUserValue(SPContext.Current.Web,
                                                                     employee[Utilities.Manager].ToString()).User.
                                                Name
                                        };
                    dataRow["Employee Name"] = entity.DisplayText.ToString();
                    dataRow["Reporting To"] = entityRep.DisplayText.ToString();

                    // var spvemptype = new SPFieldLookupValue(employee[Utilities.EmployeeType].ToString());
                    dataRow["Employee Type"] = employee[Utilities.EmployeeType].ToString();
                    var employeeLeaveList =
                        GetListItemCollection(SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeLeaves),
                                              "Employee ID", employee["Employee ID"].ToString(), "Year",
                                              hdnCurrentYear.Value);
                    foreach (SPListItem empleaves in employeeLeaveList)
                    {
                        var spv = new SPFieldLookupValue(empleaves[Utilities.LeaveType].ToString());
                        decimal leaveBalance = 0;
                        decimal total = 0;

                        leaveBalance = decimal.Parse(empleaves["Leave Balance"].ToString());
                        total = decimal.Parse(empleaves["Leave Balance"].ToString()) +
                                decimal.Parse(empleaves["Leave Requested"].ToString()) +
                                decimal.Parse(empleaves["Leave utilized"].ToString());
                        dataRow[spv.LookupValue.Trim()] = leaveBalance + "/" + total;
                    }
                    dataTable.Rows.Add(dataRow);
                }
            }

            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
            return dataTable;
        }