Ejemplo n.º 1
0
    public Stream COOR_IMAGE(Stream postParam)
    {
        if (!AMSCSRFCore.IsRequestComeFromProxy(HttpContext.Current.Request))
        {
            return(GenerateErrorResponse(null, "Requester IP is not authorized", System.Net.HttpStatusCode.Forbidden));
        }

        QueryParameter queryParameter = null;
        QueryResult    queryResult    = null;

        try
        {
            queryParameter = new QueryParameter(postParam);
            queryResult    = new QueryResult();
            Dictionary <string, object> coor = null;
            if (queryParameter.Files != null)
            {
                FileParameter fileParameter = queryParameter.Files[0];
                string        imagePath     = Path.Combine(fileParameter.File.DirectoryName, fileParameter.File.Name);
                Image         imageFile     = Image.FromFile(imagePath);
                coor = AMSCore.CoordinateImage(imageFile);
            }
            else
            {
                coor = AMSCore.CoordinateImage(queryParameter["IMAGE_URL"].ToString());
            }
        }
        catch (Exception ex)
        {
            queryResult = new QueryResult(ex);
        }

        return(queryResult.ToStream());
    }
Ejemplo n.º 2
0
        public List <Dictionary <string, object> > GetMemberofGroup(string adspath)
        {
            List <Dictionary <string, object> > groupMemebers = new List <Dictionary <string, object> >();

            try
            {
                DirectoryEntry         ent  = new DirectoryEntry(adspath);
                DirectorySearcher      srch = new DirectorySearcher(ent);
                SearchResultCollection coll = srch.FindAll();
                string USERNAME_FIELD       = !string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_USERNAME_FIELD")) ? AMSCore.WebConfigReadKey("AD_USERNAME_FIELD") : "SAMAccountName";
                foreach (SearchResult rs in coll)
                {
                    ResultPropertyCollection resultPropColl = rs.Properties;
                    foreach (Object memberColl in resultPropColl["member"])
                    {
                        DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
                        System.DirectoryServices.PropertyCollection subgroupProps = gpMemberEntry.Properties;
                        groupMemebers.Add(GetGroupsMember(subgroupProps, new Dictionary <string, object>()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
                //return groupMemebers;
            }
            return(groupMemebers);
        }
Ejemplo n.º 3
0
        private Dictionary <string, object> GetGroupsMember(PropertyCollection subgroupProps, Dictionary <string, object> subgroup)
        {
            if (subgroupProps.Contains("member"))
            {
                var subgroupMember = new List <Dictionary <string, object> >();
                foreach (Object subgroupProp in subgroupProps["member"])
                {
                    DirectoryEntry sub_gpMemberEntry = new DirectoryEntry("LDAP://" + subgroupProp);
                    var            new_subgroupProps = sub_gpMemberEntry.Properties;
                    subgroupMember.Add(GetGroupsMember(new_subgroupProps, subgroup));
                }
                foreach (Object subgroupProp in subgroupProps["cn"])
                {
                    subgroup.Add(subgroupProp.ToString(), subgroupMember);
                }

                return(subgroup);
            }
            else
            {
                var    userDetail     = new Dictionary <string, object>();
                var    userProps      = subgroupProps;
                string USERNAME_FIELD = !string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_USERNAME_FIELD")) ? AMSCore.WebConfigReadKey("AD_USERNAME_FIELD") : "SAMAccountName";
                object obVal          = userProps[USERNAME_FIELD].Value;
                if (null != obVal)
                {
                    userDetail.Add(USERNAME_FIELD, obVal.ToString());
                }
                return(userDetail);
            }
        }
Ejemplo n.º 4
0
    public static bool IsRequestComeFromProxy(HttpRequest Request)
    {
        if (AMSCore.WebConfigReadKey("ENABLE_DATASERVICE_ACCESS_FROM_PROXY_SERVER_ONLY") == "true")
        {
            string visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (string.IsNullOrEmpty(visitorIPAddress))
            {
                visitorIPAddress = HttpContext.Current.Request.UserHostAddress;
            }

            if (string.IsNullOrEmpty(visitorIPAddress))
            {
                visitorIPAddress = string.Empty;
            }

            string        ipListStr = AMSCore.WebConfigReadKey("PROXY_SERVER_IP");
            List <string> ipList    = ipListStr.Split(new char[] { '|' }).Select(ipStr => ipStr.Trim()).ToList();

            if (ipList.Contains(visitorIPAddress))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        else
        {
            return(true);
        }
    }
Ejemplo n.º 5
0
 public ActiveDirConnector()
 {
     //set Path and Domain parameter from the web config
     Path            = AMSCore.WebConfigReadKey("AD_PATH");
     Domain          = AMSCore.WebConfigReadKey("AD_DOMAIN");
     DefaultUserName = AMSCore.WebConfigReadKey("AD_USERNAME");
     DefaultPassword = AMSCore.WebConfigReadKey("AD_PASSWORD");
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Connects to a UNC path using the credentials supplied.
 /// </summary>
 /// <param name="UNCPath">Fully qualified domain name UNC path</param>
 /// <returns>True if mapping succeeds.  Use LastError to get the system error code.</returns>
 public bool NetUseWithCredentials(string UNCPath)
 {
     sUNCPath  = UNCPath;
     sUser     = AMSCore.WebConfigReadKey("UNC_USERNAME");
     sPassword = AMSCore.WebConfigReadKey("UNC_PASSWORD");
     sDomain   = AMSCore.WebConfigReadKey("UNC_DOMAIN");
     return(NetUseWithCredentials());
 }
Ejemplo n.º 7
0
        public List <Dictionary <string, object> > GetGroupNameMemberOf()
        {
            var    groupName   = new List <Dictionary <string, object> >();
            string memberField = !string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_MEMBER_FIELD")) ? AMSCore.WebConfigReadKey("AD_MEMBER_FIELD") : "memberOf";
            //var temp = Search("", "", new string[] { "adspath","name"});
            //foreach (Dictionary<string, object> name in temp)
            //{


            //        Dictionary<string, object> groupDetail = new Dictionary<string, object>();
            //        if (name.ContainsKey("adspath") && name.ContainsKey("name"))
            //        {
            //            object adspath;
            //            name.TryGetValue("adspath", out adspath);
            //            object nameG;
            //            name.TryGetValue("name", out nameG);
            //            groupDetail.Add("adspath", adspath.ToString());
            //            groupDetail.Add("name", nameG.ToString());
            //            if (!groupName.Contains(groupDetail))
            //            {

            //                groupName.Add(groupDetail);
            //            }

            //        }

            //}
            DirectoryEntry    ent    = new DirectoryEntry(Path);
            DirectorySearcher search = new DirectorySearcher(ent);
            string            query  = "(&(objectCategory=person)(objectClass=user)(memberOf=*))";

            search.Filter = query;
            //var outputFields = new string[]{ "memberOf"};
            //search.PropertiesToLoad.AddRange(outputFields);
            SearchResultCollection mySearchResultColl = search.FindAll();

            foreach (SearchResult result in mySearchResultColl)
            {
                ResultPropertyCollection resultPropColl = result.Properties;

                //foreach (string prop in outputFields)
                //{

                foreach (Object memberColl in resultPropColl["memberOf"])
                {
                    Dictionary <string, object> groupDetail = new Dictionary <string, object>();
                    groupDetail.Add("adspath", Path + "/" + memberColl);
                    if (!groupName.Contains(groupDetail))
                    {
                        groupName.Add(groupDetail);
                    }
                }
                //}
            }
            return(groupName);
        }
Ejemplo n.º 8
0
    private Dictionary <string, object> MappingADFieldWithDBField(Dictionary <string, object> adUser)
    {
        Dictionary <string, object> dbUser = new Dictionary <string, object>();

        dbUser.Add("USER_ID", adUser[AMSCore.WebConfigReadKey("USERNAME_FIELD").ToLower()]);
        dbUser.Add("ROLE_ID", adUser[AMSCore.WebConfigReadKey("MEMBER_FIELD").ToLower()]);
        dbUser.Add("NAME", adUser["name"]);
        dbUser.Add("LOGIN", adUser[AMSCore.WebConfigReadKey("USERNAME_FIELD").ToLower()]);
        return(dbUser);
    }
Ejemplo n.º 9
0
    //--------------//

    public UserProfile(Connector.QueryParameter queryParam)
    {
        //queryParam -> content from client
        FullName = System.IO.Path.Combine(
            AMSCore.WebConfigReadKey("PATH_UPLOAD_UM"), //system path from web.config
            queryParam["IMG"].ToString()                //filename from client
            );
        FileName        = string.Empty;
        FileContentType = null;
        FileContent     = null;
    }
Ejemplo n.º 10
0
    //--------------//

    public Sample(Connector.QueryParameter queryParam)
    {
        //queryParam -> content from client
        FullName = System.IO.Path.Combine(
            AMSCore.WebConfigReadKey("TEMPORARY_PATH"), //system path from web.config
            queryParam["SAMPLE_PARAM"] + ".zip"         //filename from client
            );
        FileName        = "ทดสอบ_Download_Files.zip";
        FileContentType = null;
        FileContent     = null;
    }
Ejemplo n.º 11
0
        public List <Dictionary <string, object> > Search(string filtertText)
        {
            var filterField = new string[] { };

            if (!string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_SEARCH_FIELDS")))
            {
                //The input string is in the "xxxx,xx,xxxxx" format.
                //It has to be transformed to an array of string.
                filterField = AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_SEARCH_FIELDS").Split(',');
            }
            return(Search(filtertText, filterField));
        }
Ejemplo n.º 12
0
    public static bool IsValidAuthen(HttpRequest Request, HttpSessionState Session, out string errorMessage)
    {
        string userID       = "";
        string cookieToken  = "";
        string sessionToken = "";

        if (Session["DVS_USER_ID"] != null)
        {
            userID = Session["DVS_USER_ID"].ToString();
        }

        if (Request.Cookies["AUTHEN_TOKEN"] != null)
        {
            cookieToken = Request.Cookies["AUTHEN_TOKEN"].Value;
        }

        if (Session["AUTHEN_TOKEN"] != null)
        {
            sessionToken = Session["AUTHEN_TOKEN"].ToString();
        }

        errorMessage = "";

        if (!string.IsNullOrEmpty(sessionToken) && sessionToken == cookieToken)
        {
            if (AMSCore.WebConfigReadKey("ENABLE_DUPLICATE_AUTHEN_CHECKING") == "true")
            {
                if (IsTokenMatchInDatabase(userID, sessionToken))
                {
                    return(true);
                }
                else
                {
                    //Duplicate login detected.
                    errorMessage = "DUPLICATE_LOGIN";
                    return(false);
                }
            }
            else
            {
                return(true);
            }
        }
        else if (Session["DVS_IS_GUEST"] != null && (bool)Session["DVS_IS_GUEST"] == true)
        {
            return(true);
        }
        else
        {
            errorMessage = "NOT_AUTHORIZED";
            return(false);
        }
    }
Ejemplo n.º 13
0
    public Stream CRATE_THUMBNAIL(Stream postParam)
    {
        if (!AMSCSRFCore.IsRequestComeFromProxy(HttpContext.Current.Request))
        {
            return(GenerateErrorResponse(null, "Requester IP is not authorized", System.Net.HttpStatusCode.Forbidden));
        }

        QueryParameter queryParameter = null;
        QueryResult    queryResult    = null;

        try
        {
            queryParameter = new QueryParameter(postParam);
            queryResult    = new QueryResult();
            if (queryParameter.Files != null)
            {
                FileParameter fileParameter = queryParameter.Files[0];
                string        imagePath     = Path.Combine(fileParameter.File.DirectoryName, fileParameter.File.Name);
                Image         imageFile     = Image.FromFile(imagePath);
                Image         img           = AMSCore.CreateThumbnail(imageFile, queryParameter);



                string[] fileName = queryParameter.Files[0].Name.Split('.');
                string   fileSave = fileParameter.File.DirectoryName + "\\" + fileName[0] + "_Thumbnail" + "." + fileName[fileName.Length - 1].ToString();

                //  Core.FixedSize(imageFile, 256, 256);


                //using (var canvas = Graphics.FromImage(img))
                //{


                //}



                //  img.Save(fileSave, imageFile.RawFormat);
            }
            //else
            //{
            //    string imageUrl = queryParameter["IMAGE_URL"].ToString();
            //    Core.ResizeImage(imageUrl, queryParameter);
            //}
        }
        catch (Exception ex)
        {
            queryResult = new QueryResult(ex);
        }

        return(queryResult.ToStream());
    }
Ejemplo n.º 14
0
        public Dictionary <string, object> GetUserDetail(string username)
        {
            var outputFields = new string[] { };

            if (!string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_DETAIL_FIELDS")))
            {
                //The input string is in the "xxxx,xx,xxxxx" format.
                //It has to be transformed to an array of string.
                outputFields = AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_DETAIL_FIELDS").Split(',');
            }
            string usernameField = !string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_USERNAME_FIELD")) ? AMSCore.WebConfigReadKey("AD_USERNAME_FIELD") : "SAMAccountName";

            return(Search(username, usernameField, outputFields).Count() > 0 ? Search(username, usernameField, outputFields)[0] : new Dictionary <string, object>());
        }
Ejemplo n.º 15
0
    public Stream DS_I_USER(Stream requestStream)
    {
        if (!AMSCSRFCore.IsRequestComeFromProxy(HttpContext.Current.Request))
        {
            return(GenerateErrorResponse(null, "Requester IP is not authorized", System.Net.HttpStatusCode.Forbidden));
        }

        QueryParameter queryParam  = null;
        QueryResult    queryResult = null;

        try
        {
            queryParam = new QueryParameter(requestStream);
            var SavePath = AMSCore.WebConfigReadKey("PATH_UPLOAD_UM");
            if (queryParam.Files != null && queryParam.Files.Count > 0)
            {
                if (NetworkConnector.Access(SavePath))
                {
                    if (!string.IsNullOrEmpty(queryParam.Parameter["IMG"].ToString()))
                    {
                        string path = Path.Combine(AMSCore.WebConfigReadKey("PATH_UPLOAD_UM"), queryParam.Parameter["IMG"].ToString());
                        if (File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }

                    var FileName = DateTime.Now.Ticks.ToString() + Path.GetFileName(queryParam.Files[0].Name);
                    queryParam.Files[0].Save(SavePath, FileName);
                    queryParam.Parameter["IMG"] = FileName;
                }
            }
            else
            {
                // queryParam.Parameter["IMG" FileName);
            }
            queryResult = new QueryResult();
            queryResult.AddOutputParam("success", true);
            queryResult.AddOutputParam("params", queryParam.Parameter);
        }
        catch (Exception ex)
        {
            queryResult = new QueryResult(ex);
        }
        return(queryResult.ToStream(true));
    }
Ejemplo n.º 16
0
    public Stream DS_SAMPLE_FILE_UPLOAD(Stream requestStream)
    {
        if (!AMSCSRFCore.IsRequestComeFromProxy(HttpContext.Current.Request))
        {
            return(GenerateErrorResponse(null, "Requester IP is not authorized", System.Net.HttpStatusCode.Forbidden));
        }

        IDatabaseConnector dbConnector = new DatabaseConnectorClass();
        QueryParameter     queryParam  = new QueryParameter(requestStream);
        QueryResult        queryResult = dbConnector.ExecuteStoredProcedure(queryParam);
        string             targetPath  = AMSCore.WebConfigReadKey("TEMPORARY_PATH");

        if (NetworkConnector.Access(targetPath))
        {
            foreach (FileParameter fileParameter in queryParam.Files)
            {
                fileParameter.Save(targetPath);
            }
        }
        return(queryResult.ToStream(true));
    }
Ejemplo n.º 17
0
    public Stream SEND_MAIL(Stream postParam)
    {
        if (!AMSCSRFCore.IsRequestComeFromProxy(HttpContext.Current.Request))
        {
            return(GenerateErrorResponse(null, "Requester IP is not authorized", System.Net.HttpStatusCode.Forbidden));
        }

        QueryParameter queryParameter = null;
        QueryResult    queryResult    = null;

        try
        {
            queryParameter = new QueryParameter(postParam);
            queryResult    = new QueryResult();
            AMSCore.SendEmail(queryParameter);
            return(queryResult.ToStream());
        }
        catch (Exception ex)
        {
            queryResult = new QueryResult(ex);
        }
        return(queryResult.ToStream());
    }
Ejemplo n.º 18
0
 public DatabaseConnectorClass()
     : this(AMSCore.GetConnectionString())
 {
 }
Ejemplo n.º 19
0
    public static Image FixedSizeThumbnail(Image imgPhoto, Connector.QueryParameter queryParameter)
    {
        int Width  = Int32.Parse(queryParameter["WIDTH"].ToString());
        int Height = Int32.Parse(queryParameter["HEIGHT"].ToString());

        int sourceWidth  = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX      = 0;
        int sourceY      = 0;
        int destX        = 0;
        int destY        = 0;

        float nPercent  = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);
        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
            destX    = System.Convert.ToInt16((Width -
                                               (sourceWidth * nPercent)) / 2);
        }
        else
        {
            nPercent = nPercentW;
            destY    = System.Convert.ToInt16((Height -
                                               (sourceHeight * nPercent)) / 2);
        }

        int destWidth  = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(Width, Height,
                                    PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                              imgPhoto.VerticalResolution);


        bmPhoto.MakeTransparent(Color.Transparent);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        grPhoto.Clear(Color.Transparent);



        grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
                          new Rectangle(destX, destY, destWidth, destHeight),
                          new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                          GraphicsUnit.Pixel);

        grPhoto.Dispose();
        string targetPath = AMSCore.WebConfigReadKey("THUMBNAIL_PATH");

        string[] fileName = queryParameter.Files[0].Name.Split('.');

        string fileSave = targetPath + "\\" + fileName[0] + "_Thumbnail" + "." + fileName[fileName.Length - 1].ToString();

        bmPhoto.Save(fileSave, ImageFormat.Png);
        return(bmPhoto);
    }
Ejemplo n.º 20
0
    //public static bool SendEmail(Dictionary<string, object> jsonParams)
    //{
    //    try
    //    {
    //        System.Configuration.AppSettingsReader appSettingReader = new System.Configuration.AppSettingsReader();
    //        char _splitMail = ';';
    //        string sysPath = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["gallerySysPath"]);

    //        using (MailMessage _mailMessage = new MailMessage())
    //        {

    //            string username = appSettingReader.GetValue("CREDENTIAL_USER", typeof(string)).ToString();
    //            string password = appSettingReader.GetValue("CREDENTIAL_PASS", typeof(string)).ToString();
    //            //string host = appSettingReader.GetValue("smtp_host", typeof(string)).ToString();
    //            //int port = Convert.ToInt32(appSettingReader.GetValue("smtp_port", typeof(int)));
    //            string defaultEmail = appSettingReader.GetValue("EMAILFROM", typeof(string)).ToString();
    //            NetworkCredential _credential = new NetworkCredential(username, password);

    //            if (!string.IsNullOrEmpty(jsonParams["MAILFROM"].ToString()))
    //            {
    //                defaultEmail = jsonParams["MAILFROM"].ToString();
    //            }

    //            _mailMessage.From = new MailAddress(defaultEmail);

    //            if (!string.IsNullOrEmpty(jsonParams["MAILTO"].ToString()))
    //            {
    //                string[] _arrTo = jsonParams["MAILTO"].ToString().Split(_splitMail);

    //                _arrTo.ToList<string>().ForEach(t => _mailMessage.To.Add(new MailAddress(t)));
    //            }

    //            if (!string.IsNullOrEmpty(jsonParams["MAILCC"].ToString()))
    //            {
    //                string[] _arrCC = jsonParams["MAILCC"].ToString().Split(_splitMail);

    //                _arrCC.ToList<string>().ForEach(

    //                    t => _mailMessage.CC.Add(new MailAddress(t))

    //                    );
    //            }

    //            if (!string.IsNullOrEmpty(jsonParams["MAILBCC"].ToString()))
    //            {
    //                string[] _arrBcc = jsonParams["MAILCC"].ToString().Split(_splitMail);

    //                _arrBcc.ToList<string>().ForEach(t => _mailMessage.Bcc.Add(new MailAddress(t)));
    //            }


    //            if (jsonParams["ATTACHMENTS"] != null && !string.IsNullOrEmpty(jsonParams["ATTACHMENTS"].ToString()))
    //            {

    //                string[] _arrBcc = jsonParams["ATTACHMENTS"].ToString().Split('|');

    //                for (int i = 0; i < _arrBcc.Length; i++)
    //                {
    //                    string path = Path.Combine(sysPath, _arrBcc[i].Replace("/", "\\"));
    //                    _mailMessage.Attachments.Add(new System.Net.Mail.Attachment(path));
    //                }

    //            }


    //            _mailMessage.Subject = jsonParams["MAILSUBJECT"].ToString();
    //            _mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
    //            _mailMessage.Body = jsonParams["MAILBODY"].ToString();
    //            _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
    //            _mailMessage.IsBodyHtml = true;
    //            _mailMessage.Priority = MailPriority.Normal;

    //            //using (SmtpClient _smtpClient = new SmtpClient("CDGEMAIL.cdg.co.th"))
    //            using (SmtpClient _smtpClient = new SmtpClient())
    //            {

    //                _smtpClient.UseDefaultCredentials = false;
    //                //   _smtpClient.EnableSsl = true;
    //                _smtpClient.Credentials = _credential;
    //                //   _smtpClient.Port = port;

    //                _smtpClient.Send(_mailMessage);
    //            }


    //        }
    //        return true;
    //    }
    //    catch (SmtpFailedRecipientsException ex)
    //    {
    //        throw new Exception(ex.Message);
    //    }
    //    catch (Exception ex)
    //    {
    //        throw new Exception(ex.Message);
    //    }
    //}

    public static bool SendEmail(Connector.QueryParameter queryParameter)
    {
        try
        {
            char splitMail = ';';
            using (MailMessage mailMessage = new MailMessage())
            {
                string server = AMSCore.WebConfigReadKey("EMAIL_SERVER");
                string port   = AMSCore.WebConfigReadKey("EMAIL_PORT");

                string            username     = AMSCore.WebConfigReadKey("EMAIL_CREDENTIAL_USER");
                string            password     = AMSCore.WebConfigReadKey("EMAIL_CREDENTIAL_PASS");
                string            defaultEmail = AMSCore.WebConfigReadKey("EMAIL_FROM");
                NetworkCredential credential   = new NetworkCredential(username, password);
                if (queryParameter["MAIL_FROM"] != null && !string.IsNullOrEmpty(queryParameter["MAIL_FROM"].ToString()))
                {
                    defaultEmail = queryParameter["MAIL_FROM"].ToString();
                }
                mailMessage.From = new MailAddress(defaultEmail);

                if (queryParameter["MAIL_TO"] != null && !string.IsNullOrEmpty(queryParameter["MAIL_TO"].ToString()))
                {
                    string[] arrTo = queryParameter["MAIL_TO"].ToString().Split(splitMail);
                    arrTo.ToList <string>().ForEach(t => mailMessage.To.Add(new MailAddress(t)));
                }

                if (queryParameter["MAIL_CC"] != null && !string.IsNullOrEmpty(queryParameter["MAIL_CC"].ToString()))
                {
                    string[] arrCC = queryParameter["MAIL_CC"].ToString().Split(splitMail);
                    arrCC.ToList <string>().ForEach(t => mailMessage.CC.Add(new MailAddress(t)));
                }

                if (queryParameter["MAIL_BCC"] != null && !string.IsNullOrEmpty(queryParameter["MAIL_BCC"].ToString()))
                {
                    string[] arrBcc = queryParameter["MAIL_BCC"].ToString().Split(splitMail);
                    arrBcc.ToList <string>().ForEach(t => mailMessage.Bcc.Add(new MailAddress(t)));
                }

                if (queryParameter.Files != null && queryParameter.Files.Count > 0)
                {
                    foreach (Connector.FileParameter fileParameter in queryParameter.Files)
                    {
                        mailMessage.Attachments.Add(new System.Net.Mail.Attachment(fileParameter.File.FullName));
                    }
                }

                mailMessage.Subject         = queryParameter["MAIL_SUBJECT"].ToString();
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
                mailMessage.Body            = queryParameter["MAIL_BODY"].ToString();
                mailMessage.BodyEncoding    = System.Text.Encoding.UTF8;
                mailMessage.IsBodyHtml      = true;
                mailMessage.Priority        = MailPriority.Normal;

                using (SmtpClient smtpClient = new SmtpClient(server, int.Parse(port)))
                {
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials           = credential;
                    smtpClient.EnableSsl             = true;
                    smtpClient.Send(mailMessage);
                }
            }
            return(true);
        }
        catch (SmtpFailedRecipientsException ex)
        {
            throw new Exception(ex.Message);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
Ejemplo n.º 21
0
        public List <Dictionary <string, object> > Search(string filtertText, string[] filterFields, string[] outputFields)
        {
            List <Dictionary <string, object> > userDetails = new List <Dictionary <string, object> >();

            try
            {
                Object obj = entry.NativeObject;

                DirectorySearcher search = new DirectorySearcher(entry);

                if (filterFields.Count() > 0)
                {
                    search.Filter = GetFilterText(filtertText, filterFields);
                }
                string[] requiredProps = { };
                if (!string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_FIELDS")))
                {
                    //The input string is in the "xxxx,xx,xxxxx" format.
                    //It has to be transformed to an array of string.
                    requiredProps = AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_FIELDS").Split(',');
                    outputFields  = outputFields.Union(requiredProps).ToArray <string>();
                }
                search.PropertiesToLoad.AddRange(outputFields);
                foreach (SearchResult result in search.FindAll())
                {
                    if (result != null)
                    {
                        Dictionary <string, object> userDetail = new Dictionary <string, object>();
                        if (outputFields.Length > 0)
                        {
                            ResultPropertyCollection resultPropColl = result.Properties;
                            foreach (string prop in outputFields)
                            {
                                foreach (Object memberColl in resultPropColl[prop])
                                {
                                    userDetail.Add(prop, memberColl);
                                }
                            }
                        }
                        else
                        {
                            var enumEntry = result.Properties.GetEnumerator();
                            while (enumEntry.MoveNext())
                            {
                                object value = enumEntry.Value;
                                if (value is DateTime)
                                {
                                    value = Util.DateTimeToString(value as DateTime?);
                                }
                                userDetail.Add(enumEntry.Key.ToString(), value);
                            }
                        }
                        userDetails.Add(userDetail);
                    }
                }
            }
            catch// (Exception ex)
            {
                return(userDetails);
            }
            finally
            {
                //_DirectoryEntry.GetMethod("Close").Invoke(entry, new object[] { });
            }
            return(userDetails);
        }
Ejemplo n.º 22
0
    protected void ApplicationLogin(string storeName)
    {
        Connector.QueryParameter loginParameter = new Connector.QueryParameter(Request);
        Connector.QueryResult    loginResult    = null;
        try
        {
            if (loginParameter.Parameter != null && loginParameter.Parameter.ContainsKey("USERNAME") && loginParameter.Parameter.ContainsKey("PASSWORD"))
            {
                if (loginParameter["USERNAME"].Equals(Encoding.UTF8.GetString(Convert.FromBase64String(hdUSername))) &&
                    loginParameter["PASSWORD"].Equals(Encoding.UTF8.GetString(Convert.FromBase64String(hdPassword))))
                {
                    //for hidden user
                    loginResult           = new Connector.QueryResult();
                    loginResult.Success   = true;
                    loginResult.Message   = "";
                    loginResult.DataTable = new DataTable();
                    loginResult.DataTable.Columns.Add("USER_ID", typeof(string));
                    loginResult.DataTable.Rows.Add(new object[] { "999999999" });
                }
                else
                {
                    if (AMSCore.WebConfigReadKey("AUTHENTICATION_TYPE") == "1")
                    {
                        loginResult = AuthenByDB(storeName, loginParameter);
                    }
                    else if (AMSCore.WebConfigReadKey("AUTHENTICATION_TYPE") == "2")
                    {
                        loginResult = AuthenByAD(loginParameter);
                    }
                    else if (AMSCore.WebConfigReadKey("AUTHENTICATION_TYPE") == "3")
                    {
                        loginResult = AuthenByAD(loginParameter);
                        if (loginResult == null || !loginResult.Success)
                        {
                            loginResult = AuthenByDB(storeName, loginParameter);
                        }
                    }
                }
            }
            else
            {
                throw new Exception("ERROR_REQUIRED_USER");
                //ERROR_INVALID_LOGIN: "******",
                //ERROR_INVALID_USER: "******",
                //ERROR_INVALID_PASSWORD: "******",
                //ERROR_NO_PERMISSION: "ชื่อผู้ใช้งานนี้ไม่มีสิทธิ์การใช้งาน"
                //loginResult.Message = "ERROR_INVALID_LOGIN";
            }
        }
        catch (Exception ex)
        {
            loginResult = new Connector.QueryResult(ex);
        }

        if (loginResult.Success)
        {
            string userID = Session["DVS_USER_ID"].ToString();
            string token  = AMSDuplicateAuthenCore.GenerateToken();

            Session["AUTHEN_TOKEN"] = token;

            if (AMSCore.WebConfigReadKey("ENABLE_DUPLICATE_AUTHEN_CHECKING") == "true")
            {
                AMSDuplicateAuthenCore.StoreToken(userID, token);
            }

            HttpCookie authenTokenCookie = new HttpCookie("AUTHEN_TOKEN");
            authenTokenCookie.Value = token;
            Response.Cookies.Add(authenTokenCookie);
        }

        Response.ContentType = "application/json";
        Response.Write(loginResult.ToJson());
    }
Ejemplo n.º 23
0
    protected bool PageSelector(string request, out string wgNamespace, out Dictionary <string, object> wgParameters)
    {
        wgNamespace  = string.Empty;
        wgParameters = new Dictionary <string, object>();

        switch (request)
        {
        case "portal":
            wgNamespace = "viewer/Portal/Portal";
            if (Session != null && Session["DVS_USER_ID"] != null)
            {
                if (!checkAuthentication())
                {
                    return(false);
                }

                if (AMSCore.WebConfigReadKey("AUTHENTICATION_TYPE") == "1")
                {
                    wgParameters = new Dictionary <string, object>()
                    {
                        { "permission", GetSystemPermission(Session["DVS_USER_ID"].ToString()).ToDictionary() }
                    };
                }
                else if (AMSCore.WebConfigReadKey("AUTHENTICATION_TYPE") == "2")
                {
                    wgParameters = new Dictionary <string, object>()
                    {
                        { "permission", AuthenByAD(Session["DVS_USER_ID"].ToString()).ToDictionary() }
                    };
                }
                else if (AMSCore.WebConfigReadKey("AUTHENTICATION_TYPE") == "3")
                {
                }
            }
            else if (AMSCore.WebConfigReadKey("GUEST_ENABLED") != null && AMSCore.WebConfigReadKey("GUEST_ENABLED").Equals("1"))
            {
                Session["DVS_IS_GUEST"] = true;
                Session["DVS_USER_ID"]  = AMSCore.WebConfigReadKey("GUEST_USER_ID");
                wgParameters            = new Dictionary <string, object>()
                {
                    { "permission", GetSystemPermission(Session["DVS_USER_ID"].ToString()).ToDictionary() }
                };
            }
            break;

        case "logout":
        {
            ApplicationLogout(Session, Response);
            if (Request.HttpMethod != "POST")
            {
                Response.Redirect("~/", true);
            }
            return(false);
        }

        case "system":
            if (Request.HttpMethod == "POST")
            {
                Response.ClearContent();

                Connector.QueryParameter reqParameter = new Connector.QueryParameter(Request);
                if (reqParameter["SYS_ID"].Equals("-1"))
                {
                    Session.Remove("DVS_SYSTEM_ID");
                }
                else
                {
                    Session["DVS_SYSTEM_ID"] = reqParameter["SYS_ID"];
                }
                Response.ContentType = "application/json";
                Response.Write(new Connector.QueryResult().ToJson());

                return(false);
            }
            else if (!checkAuthentication())
            {
                return(false);
            }

            break;

        case "forgetPassword":
        {
            wgNamespace  = "viewer/ForgetPassword/ForgetPassword";
            wgParameters = new Dictionary <string, object>()
            {
                { "token", Request.Params["token"] },
                { "userid", Request.Params["userid"] },
                { "forgetByEmail", true }
            };
            break;
        }

        case "APP_Q_LOGIN":
        {
            Response.ClearContent();

            ApplicationLogin("APP_Q_LOGIN");
            return(false);
        }

        case "UM_Q_VERIFY_USER":
        case "UM_U_PWD":
        case "UM_U_RESET_PWD":
        case "UM_Q_MAIL_TOKEN":
        {
            Response.ClearContent();

            string storeName = request;

            Connector.IDatabaseConnector dbConnector  = new Connector.DatabaseConnectorClass();
            Connector.QueryParameter     reqParameter = new Connector.QueryParameter(Request);

            Connector.QueryResult logoutResult = dbConnector.ExecuteStoredProcedure(storeName, reqParameter);

            Response.ContentType = "application/json";
            Response.Write(logoutResult.ToJson());
            return(false);
        }

        default:
            break;
        }

        return(true);
    }
Ejemplo n.º 24
0
    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        //assign HTML injection configuration.
        List <string> webConfigToSetCookieList = new List <string>()
        {
            "PREVENT_HTML_INPUT",
            "ENCODE_HTML",
            "PREVENT_HTML_INPUT_CHAR_LIST"
        };

        foreach (string webConfigParam in webConfigToSetCookieList)
        {
            if (Response.Cookies[webConfigParam] == null)
            {
                HttpCookie cookie = new HttpCookie(webConfigParam);
                cookie.Value = AMSCore.WebConfigReadKey(webConfigParam);
                Response.Cookies.Add(cookie);
            }
            else
            {
                Response.Cookies[webConfigParam].Value = AMSCore.WebConfigReadKey(webConfigParam);
            }
        }

        //assign authentication token for checking authentication.
        if (Session["AUTHEN_TOKEN"] != null)
        {
            HttpCookie authenTokenCookie = new HttpCookie("AUTHEN_TOKEN");
            authenTokenCookie.Value = Session["AUTHEN_TOKEN"].ToString();
            Response.Cookies.Add(authenTokenCookie);
        }

        //assign CSRF token for checking form sending from across domain.
        if (Session["CSRF_TOKEN"] != null)
        {
            HttpCookie authenTokenCookie = new HttpCookie("CSRF_TOKEN");
            authenTokenCookie.Value = Session["CSRF_TOKEN"].ToString();
            Response.Cookies.Add(authenTokenCookie);
        }

        Response.Cache.SetNoStore();

        InsertMeta();

        Connector.QueryParameter requestParameter = new Connector.QueryParameter(Request);

        string cssDojoUrl = AMSCore.WebConfigReadKey("CSS_DOJO");
        string cssEsriUrl = AMSCore.WebConfigReadKey("CSS_ESRI");

        string jsAmosUrl  = AMSCore.WebConfigReadKey("JS_AMOS_URL");
        string cssAmosUrl = AMSCore.WebConfigReadKey("CSS_AMOS");

        /// Insert Script Tags (reverse seq.)
        /// last --> first
        InsertScriptSrc(AMSCore.WebConfigReadKey("CONFIG_ESRI") + appCacheBust);
        InsertScriptSrc(AMSCore.WebConfigReadKey("JS_API_URL") + appCacheBust);

        InitializeDojoConfig(requestParameter);

        if (jsAmosUrl.StartsWith("//"))
        {
            jsAmosUrl = "location.protocol + '" + jsAmosUrl + "'";
        }
        else
        {
            jsAmosUrl = "'" + jsAmosUrl + "'";
        }
        InsertScriptTag("dojoConfig.packages.push({'name': 'esrith', 'location': " + jsAmosUrl + "});");


        InsertScriptSrc(AMSCore.WebConfigReadKey("CONFIG_DOJO") + appCacheBust);

        /// Insert Style Tags (forward seq.)
        /// first --> last
        InsertStyleTag(
            string.Format("@import '{0}';", cssDojoUrl + appCacheBust) + "\r\n" +
            string.Format("@import '{0}';", cssEsriUrl + appCacheBust) + "\r\n" +
            string.Format("@import '{0}';", cssAmosUrl + appCacheBust)
            );

        long   timeDiff = 0;
        double timezone = 0;


        if (AMSCore.WebConfigReadKey("IS_DEBUG") == "0")
        {
            Connector.IDatabaseConnector dbConnector = new Connector.DatabaseConnectorClass();
            Connector.QueryResult        dbResult    = null;
            try
            {
                if (dbConnector.Provider == Connector.ProviderFactory.Oracle)
                {
                    dbResult = dbConnector.ExecuteStatement("select sysdate as CURRENT_DATE, dbtimezone as TIMEOFFSET from dual");
                }
                else if (dbConnector.Provider == Connector.ProviderFactory.MSSQL)
                {
                    dbResult = dbConnector.ExecuteStatement("select getdate() as CURRENT_DATE, datediff(minute, convert(time, sysutcdatetime()), convert(time, sysdatetimeoffset())) as TIMEOFFSET");
                }
            }
            catch { }

            if (dbResult.Success == true && dbResult.DataTable.Rows.Count > 0)
            {
                timeDiff = AMSCore.DateTimeToUnixTimeStamp((dbResult.DataTable.Rows[0]["CURRENT_DATE"] as DateTime?).Value);
                string timeOffset = dbResult.DataTable.Rows[0]["TIMEOFFSET"].ToString();
                if (timeOffset.StartsWith("+"))
                {
                    timezone = double.Parse("-" + AMSCore.StringToDateTime(timeOffset.Substring(1), "HH:mm").TimeOfDay.TotalMinutes.ToString());
                }
                else if (timeOffset.StartsWith("-"))
                {
                    timezone = double.Parse("+" + AMSCore.StringToDateTime(timeOffset.Substring(1), "HH:mm").TimeOfDay.TotalMinutes.ToString());
                }
                else
                {
                    timezone = double.Parse(dbResult.DataTable.Rows[0]["TIMEOFFSET"].ToString());
                }
            }
            else
            {
                TimeZone localZone     = TimeZone.CurrentTimeZone;
                DateTime currentDate   = DateTime.Now;
                TimeSpan currentOffset = localZone.GetUtcOffset(currentDate);
                timeDiff = AMSCore.DateTimeToUnixTimeStamp(currentDate, -currentOffset.TotalMinutes);
                timezone = currentOffset.TotalMinutes * -1;
            }
        }
        else
        {
            TimeZone localZone     = TimeZone.CurrentTimeZone;
            DateTime currentDate   = DateTime.Now;
            TimeSpan currentOffset = localZone.GetUtcOffset(currentDate);
            timeDiff = AMSCore.DateTimeToUnixTimeStamp(DateTime.Now, -currentOffset.TotalMinutes);
            timezone = currentOffset.TotalMinutes * -1;
        }

        //Dictionary<string, object> sessionObject = new Dictionary<string, object>();
        //Dictionary<string, object> sessionObject2 = null;
        System.Web.Script.Serialization.JavaScriptSerializer serialization = new System.Web.Script.Serialization.JavaScriptSerializer();
        StringBuilder txtScript = new StringBuilder();

        txtScript.AppendLine("try{");

        txtScript.AppendLine("Object.defineProperty(window,'appVersion',{value:'" + appVersion + "'});");
        txtScript.AppendLine("Object.defineProperty(window,'appServer',{value:{}});");
        txtScript.AppendLine("Object.defineProperty(appServer,'timeDiff',{value:" + timeDiff + " - new Date().getTime()});");
        txtScript.AppendLine("Object.defineProperty(appServer,'timeZone',{value:" + timezone + "});");
        txtScript.AppendLine("Object.defineProperty(appServer,'isDebug',{value:'" + AMSCore.WebConfigReadKey("IS_DEBUG") + "'});");
        txtScript.AppendLine("Object.defineProperty(appServer,'isEncrypt',{value:'" + AMSCore.WebConfigReadKey("IS_ENCRYPT") + "'});");
        txtScript.AppendLine("Object.defineProperty(appServer,'sessionId',{value:'" + Session.SessionID + "'});");

        Dictionary <string, object> webConfigObject = new Dictionary <string, object>();

        txtScript.AppendLine("Object.defineProperty(appServer,'webConfig',{value:{}});");
        foreach (string keyConfig in AMSCore.WebConfigKeys())
        {
            webConfigObject.Add(keyConfig, AMSCore.WebConfigReadKey(keyConfig));
            txtScript.AppendLine(string.Format(@"Object.defineProperty(appServer.webConfig,'{0}',{1});", keyConfig, serialization.Serialize(new Dictionary <string, object>()
            {
                { "value", AMSCore.WebConfigReadKey(keyConfig) }
            })));
        }
        txtScript.AppendLine("}catch(err){");
        txtScript.AppendLine("window.appVersion = '" + appVersion + "'");
        txtScript.AppendLine("window.appServer = {");
        txtScript.AppendLine("'timeDiff':" + timeDiff + " - new Date().getTime(),");
        txtScript.AppendLine("'timeZone':" + timezone + ",");
        txtScript.AppendLine("'isDebug':'" + AMSCore.WebConfigReadKey("IS_DEBUG") + "',");
        txtScript.AppendLine("'isEncrypt':'" + AMSCore.WebConfigReadKey("IS_ENCRYPT") + "',");
        txtScript.AppendLine("'sessionId':'" + Session.SessionID + "',");
        txtScript.AppendLine("'webConfig':" + serialization.Serialize(webConfigObject));
        txtScript.AppendLine("};");
        txtScript.AppendLine("}");

        //string onCloseBrowserScript = @"
        //    window.onbeforeunload = function (event)
        //    {
        //        try
        //        {
        //            var request = new XMLHttpRequest();
        //            request.open('POST','{logoutURLPath}',false);
        //            request.setRequestHeader('content-type','application/x-www-form-urlencoded');
        //            request.timeout = 4000;
        //            request.send('');
        //        }
        //        catch(err)
        //        {
        //        }
        //    };
        //";

        //string logoutURLPath = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/?p=logout");
        //onCloseBrowserScript = onCloseBrowserScript.Replace("{logoutURLPath}", logoutURLPath);

        //txtScript.AppendLine(onCloseBrowserScript);

        InsertScriptTag(txtScript.ToString());
    }
Ejemplo n.º 25
0
        //for has file & session (from proxy page)
        public QueryParameter(HttpContext reqContext)
        {
            List <string> sessionKey = new List <string>();
            List <Dictionary <string, object> > fileList = null;
            NameValueCollection appSettings = WebConfigurationManager.AppSettings;
            string tempPath = string.Empty;

            try
            {
                if (reqContext.Request.ContentType.StartsWith("multipart/form-data"))
                {
                    if (reqContext.Request.Form.Count > 0)
                    {
                        try
                        {
                            this.Parameter = new Dictionary <string, object>();
                            for (int i = 0; i < reqContext.Request.Form.Count; i++)
                            {
                                this.Parameter.Add(reqContext.Request.Form.GetKey(i), reqContext.Request.Form[i]);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                else
                {
                    _QueryParameter(reqContext.Request);
                }

                if (reqContext.Request.Files.Count > 0)
                {
                    fileList = new List <Dictionary <string, object> >();
                    tempPath = System.IO.Path.Combine(reqContext.Server.MapPath("~/"), AMSCore.WebConfigReadKey("TEMPORARY_PATH"));
                    try
                    {
                        if (NetworkConnector.Access(tempPath))
                        {
                            if (!Directory.Exists(tempPath))
                            {
                                Directory.CreateDirectory(tempPath);
                            }
                            DeleteOldFile(tempPath);
                        }
                    }
                    catch { }
                    if (this.Parameter == null)
                    {
                        this.Parameter = new Dictionary <string, object>();
                    }
                    if (!this.Parameter.ContainsKey(FILE_PARAM_NAME))
                    {
                        this.Parameter.Add(FILE_PARAM_NAME, fileList);
                    }

                    for (int i = 0; i < reqContext.Request.Files.Count; i++)
                    {
                        string fileName = reqContext.Request.Files[i].FileName;
                        if (string.IsNullOrEmpty(fileName))
                        {
                            continue;
                        }
                        string contentType = reqContext.Request.Files[i].ContentType;
                        string fileExt     = System.IO.Path.GetExtension(fileName);
                        string newFileName = string.Format("{0}-{1}{2}", DateTime.Now.Ticks, new Random().Next(999).ToString("000"), fileExt);
                        string fullName    = System.IO.Path.Combine(tempPath, newFileName);
                        if (!Directory.Exists(tempPath))
                        {
                            Directory.CreateDirectory(tempPath);
                        }
                        reqContext.Request.Files[i].SaveAs(fullName);
                        fileList.Add(new Dictionary <string, object>()
                        {
                            { "NAME", fileName },
                            { "CONTENT_TYPE", contentType },
                            { "FULLNAME", fullName }
                        });
                    }
                }
                foreach (string key in appSettings.AllKeys)
                {
                    if (!key.StartsWith(this.PREFIX_SESSION))
                    {
                        continue;
                    }
                    foreach (string replaceKey in appSettings[key].Split('|'))
                    {
                        if (!this.Parameter.ContainsKey(replaceKey))
                        {
                            continue;
                        }
                        IsUseSession = true;
                        this.Add(replaceKey, reqContext.Session[key]);
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 26
0
        public Dictionary <string, object> AuthenWithDomain(string username, string password)
        {
            Dictionary <string, object> userDetail = new Dictionary <string, object>();
            string domainAndUsername = null;

            domainAndUsername = string.Format(@"{0}\{1}", this.Domain, username);
            entry             = new DirectoryEntry(Path, domainAndUsername, password);
            try
            {
                Object obj = entry.NativeObject;

                DirectorySearcher search        = new DirectorySearcher(entry);
                string            usernameField = !string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_USERNAME_FIELD")) ? AMSCore.WebConfigReadKey("AD_USERNAME_FIELD") : "SAMAccountName";
                search.Filter = "(" + usernameField + "=" + domainAndUsername + ")";
                string[] requiredProps = { };
                if (!string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_FIELDS")))
                {
                    //The input string is in the "xxxx,xx,xxxxx" format.
                    //It has to be transformed to an array of string.
                    requiredProps = AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_FIELDS").Split(',');
                    search.PropertiesToLoad.AddRange(requiredProps);
                }
                SearchResult result = search.FindOne();
                if (result != null)
                {
                    if (requiredProps.Length > 0)//if the required property is not null or emptry
                    {
                        ResultPropertyCollection resultPropColl = result.Properties;
                        foreach (string prop in requiredProps)
                        {
                            foreach (Object memberColl in resultPropColl[prop])
                            {
                                userDetail.Add(prop, memberColl);
                            }
                        }
                    }
                    else //if the required property is null or emptry, it will return all properties.
                    {
                        var enumEntry = result.Properties.GetEnumerator();
                        while (enumEntry.MoveNext())
                        {
                            object value = enumEntry.Value;
                            if (value is DateTime)
                            {
                                value = Util.DateTimeToString(value as DateTime?);
                            }
                            userDetail.Add(enumEntry.Key.ToString(), value);
                        }
                    }
                }
            }
            catch
            {
                return(userDetail);
            }
            finally
            {
                entry.Close();
            }
            return(userDetail);
        }