History

History of .net

Monday, 4 March 2013

Check AD Authentication of the user While Login



protected void btnLogin_Click(object sender, EventArgs e)
    {
        using (HostingEnvironment.Impersonate())
        {
            string strDomain = ConfigurationManager.AppSettings["LDAPServer"];
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, strDomain))
            {
                string[] Name = txtUserName.Text.Split('\\');
                string _domainName = Name[0];
                string _userName = Name.Count() == 1 ? Name[0] : Name[1];
                // validate the credentials
                bool isValid = pc.ValidateCredentials(_userName, txtPassword.Text);
                if (isValid)
                {
                    try
                    {
                        DirectorySearcher dssearch = new DirectorySearcher(strDomain);
                        dssearch.Filter = "(SAMAccountName=" + _userName + ")";
                        SearchResult sresult = dssearch.FindOne();
                        DirectoryEntry dsresult = new DirectoryEntry();
                        dsresult = sresult.GetDirectoryEntry();

                        string sName = string.Empty, sEmailID = string.Empty;

                        if (!string.IsNullOrEmpty(dsresult.Properties["displayName"][0].ToString()))
                            sName = dsresult.Properties["displayName"][0].ToString();

                        if (dsresult.Properties["mail"].Value != null)
                            sEmailID = dsresult.Properties["mail"][0].ToString();

                        Session["STRING_SV_USERNAME"] = sName;
                        Session["STRING_SV_USER_ID"] = txtUserName.Text.Trim();
                        Session["STRING_SV_USEREMAILID"] = sEmailID;
                        Session["COMPANYID"] = ddlCompany.SelectedValue;
                        Session["COMPANY_NAME"] = ddlCompany.SelectedItem.Text;

                        Session["STRING_SV_LOGIN_STATUS"] = "Success";

                        string _companyConnStr = new CommonMethods().GetConnectionStringValueByCompanyId("1");
                        string _ShortCode = new CommonMethods().GetCompanyShortCodeByCompanyID(_companyConnStr, Convert.ToInt32(ddlCompany.SelectedValue));
                        Session["SHORTCODE"] = _ShortCode;

                        /* Code to get the authorized screens list for the logged in user */
                        objCommonMethods = new CommonMethods();

                        List<string> friendlyPageNames = objCommonMethods.GetAuthScreensListByUserIDandCompanyID(txtUserName.Text, Convert.ToInt32(ddlCompany.SelectedValue), strNewCompanyConnStr); // Change this to get the screens list

                        Session["FRIENDLY_PAGES"] = friendlyPageNames;

                        if (ddlCompany.SelectedValue != "1")
                        {
                            Session["ConfigConnectionString"] = GenerateConstr();
                        }
                        else
                        {
                            Session["ConfigConnectionString"] = ConfigurationManager.ConnectionStrings["Genpact"].ConnectionString;
                        }
                        System.Web.HttpBrowserCapabilities browser = Request.Browser;
                        Session["USER_LOGIN_ID"] = objCommonMethods.InsertUserDetails(Convert.ToString(Session["STRING_SV_USER_ID"]), browser.Browser, HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
                    }
                    catch (Exception ex)
                    {
                        Session["STRING_SV_LOGIN_STATUS"] = "Fail";
                        AlertMsg.MsgBox(Page, Resource.ERR_LOGIN);
                        txtUserName.Text = string.Empty;
                        txtPassword.Text = string.Empty;

                        objSmartViewException = new SmartViewException();
                        objSmartViewException.InsertErrorDetails(ex);
                        isValid = false;
                    }
                    if (isValid)
                    {
                        Response.Redirect("Home.aspx");
                    }
                }
                else
                {
                    Session["STRING_SV_LOGIN_STATUS"] = "Fail";
                    AlertMsg.MsgBox(Page, Resource.ERR_LOGIN);
                    txtUserName.Text = string.Empty;
                    txtPassword.Text = string.Empty;
                }
            }
        }
    }

Thursday, 14 February 2013

Get Value from Resource file dynamically


Resourcefilename.ResourceManager.GetString("KeyName");
MyFile.ResourceManager.GetString("PropertyOneName");

Thursday, 24 January 2013


Method to Add a Scheduler Dynamically through C# Code


Bfore writing this method we have to add a dll(Microsoft.Win32.TaskScheduler.dll) reference to our Application MUST
private bool CreateScheduler(string _newServicePath)
{
try
{
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Data Import Utility for " + txtShortCode.Text;
// Create a trigger that will fire the task at this time every other day
var tt = new TimeTrigger();
tt.Repetition.Interval = TimeSpan.FromMinutes(30);
td.Triggers.Add(tt);
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction(_newServicePath, null, null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(txtShortCode.Text, td);
return true;
}
}
catch (Exception ex)
{
ex.ToString();
return false;
}
}

Method to Replace a connection string in Appconfig of a Application


private bool Replaceconnectionstr(string filepath, string KeyCode, string NewConnectionString)
{
try
{
string otherExePath = @filepath;
Configuration otherConfig = ConfigurationManager.OpenExeConfiguration(otherExePath);
string otherSetting = otherConfig.AppSettings.Settings[KeyCode].Value;
otherConfig.AppSettings.Settings[KeyCode].Value = NewConnectionString;
otherConfig.Save();
return true;
}
catch (Exception ex)
{
ex.ToString();
return false;
}
}

Method to copy files and folder from one Folder to another Folder

private bool CopyFolderContents(string SourcePath, string DestinationPath)
{
SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";

try
{
if (Directory.Exists(SourcePath))
{
if (Directory.Exists(DestinationPath) == false)
{
Directory.CreateDirectory(DestinationPath);
}

foreach (string files in Directory.GetFiles(SourcePath))
{
FileInfo fileInfo = new FileInfo(files);
fileInfo.CopyTo(string.Format(@"{0}\{1}", DestinationPath, fileInfo.Name), true);
}

foreach (string drs in Directory.GetDirectories(SourcePath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(drs);
if (CopyFolderContents(drs, DestinationPath + directoryInfo.Name) == false)
{
return false;
}
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}

Wednesday, 23 January 2013

To get file Extension through file upload control

To get the extension of a uploaded file through file upload control. Path.GetExtension(FileUpload1.FileName)

Monday, 7 January 2013


How to redirect to another page after alert message?


Through HTML
Response.Write("");

Method through C# Code ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptKey", "alert('Cancel Clicked');window.location='NewMetricAddition.aspx'; ", true);