how to get cmos date/time asp.net [duplicate] - c#

This question already has an answer here:
Get BIOS date in asp.net
(1 answer)
Closed 9 years ago.
i am developing an application in asp.net of which i want to create a DEMO version for 7 days.. i tried to make the demo stop in asp.net by checking for the current date and if its past 7 days then the application. wont start.
but the problem is the user changes the date from windows control panel then application. wont detect it and it will run.. i want take cmos date/time Without Online
int num=7;
int smonth=convert.toint32(Datetime.Now.Date.Tostring());
if ((num < smonth) || (num == smonth))
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('Please Update your Licence Key');", true);
}
else
{
if (crt_val == "0")
{
Session["UserId"] = txtusername.Text.Trim();
objuser.UserCode = txtusername.Text.Trim();
objuser.Password = s_hex_md5(txtpassword.Text.Trim());
string pwd = s_hex_md5(txtpassword.Text);
objuser.Ccode = ddlCode.SelectedValue;
objuser.Lcode = ddlLocation.SelectedValue;
DataTable dt = new DataTable();
dt = objdata.UserLogin(objuser);
if (dt.Rows.Count > 0)
{
if ((dt.Rows[0]["UserCode"].ToString().Trim() == txtusername.Text.Trim()) && (dt.Rows[0]["Password"].ToString().Trim() == pwd) && (dt.Rows[0]["CompCode"].ToString().Trim() == ddlCode.SelectedValue) && (dt.Rows[0]["LocationCode"].ToString().Trim() == ddlLocation.SelectedValue))
{
Session["Isadmin"] = dt.Rows[0]["IsAdmin"].ToString().Trim();
Session["Usernmdisplay"] = txtusername.Text.Trim();
Session["Ccode"] = dt.Rows[0]["CompCode"].ToString().Trim();
Session["Lcode"] = dt.Rows[0]["LocationCode"].ToString().Trim();
if (Session["Isadmin"].ToString() == "1")
{
Session["RoleCode"] = "1";
}
else
{
Session["RoleCode"] = "2";
}
Response.Redirect("Dashboard.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('User Name and Password Wrong');", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('Please Update your Licence Key');", true);
}
}
else
{ }
}
Anyone help me...

When user changes the time in control panel, the user IS changing the CMOS date/time.
You might want to have your application contact a time server online to get the correct date/time.
Excellent answer on how to do it here
https://stackoverflow.com/a/12150289/263003

DateTime structure in C# gives you the date and time details from the machine where the code is running. so if you want to give a demo application to the client you can deploy the application on the Server which is under your control. so that user does not have the control to change the date and time, even if the client changes date and time it wont effect the Application as the Application code is running on different machine.
DateTime.Now gives you the Current date and time of the Server
so i would suggest to maintain a dedicated server for deploying/maintaining the website for client.

Related

ASP.NET page stops processing

I'm having a hard time with what appears to be a connection issue. I have scoured the web and sounds like this is not the way to go but if someone has any thoughts or ideas that would be great.
I have a hunch it's because these 4 pages are using the same .cs code file and all logic is happening OnLoad() so it is kicking the other off? These reports are for display only, no input required from user.
Please let me know if more information is needed, thank you!
Issue:
Page loads fine on its own but if multiple tabs are ran and one is still processing, it halts this and then displays missing data and formatting. Can sometimes be mimicked by pressing refresh (F5) twice quickly.
Environment:
IIS running on server
DB2Database (IBM)
Web Report:
4 asp.net pages that link to same Default.CS code file (ex. /dash/steel.aspx, /dash/steelnums.aspx)
On page load > read CSV files using StreamReader > run SQL query > format/display information into data grid view
Connection Example:
iDB2Connection BlueDB2Connection = new iDB2Connection(strConnectionString);
iDB2DataAdapter BlueDB2PartsDataAdapter = new iDB2DataAdapter();
iDB2Command SqlCmd = BlueDB2Connection.CreateCommand();
SqlCmd.CommandTimeout = 1000000000;
// select proper query based on page being loaded
if (curPage.Contains("amewood"))
{
SqlCmd.CommandText = sqlMainDataWood();
}
else if (curPage.Contains("amesteel"))
{
SqlCmd.CommandText = sqlMainDataSteel();
}
BlueDB2PartsDataAdapter.SelectCommand = SqlCmd;
try
{
BlueDB2PartsDataAdapter.Fill(dsParts);
}
catch (SqlException sqlEx)
{
DisplayError.Text = "Error:" + sqlEx.Message;
}
Reading CSV function:
using (StreamReader reader = new StreamReader(basePath + filePath + "daysStart.csv"))
{
var headerLine = reader.ReadLine();
var line = reader.ReadToEnd();
var values = line.Split(',');
DateTime dt;
DateTime today = DateTime.ParseExact(DateTime.Now.ToString("MMddyyyy"), "MMddyyyy", CultureInfo.InvariantCulture);
int i = 0;
if (values.Length != 0)
{
foreach (string item in values)
{
if (item != "")
{
dt = DateTime.ParseExact(item, "MMddyyyy", CultureInfo.InvariantCulture);
dateData.startDate = dt;
}
else
{
dateData.startDate = today;
}
i++;
}
}
else
{
dateData.startDate = today;
}
}
Troubleshooting:
Attempted multiple threading
Tried delays prior to code
Tested that the CSV's were not causing the issue
Not closing the DB connection (disposing it) would be the culprit. After running every command or query, you have to dispose of the connection (or at the end of the event handler function). As #Dai suggested if you're not limited to using DB2 and Web Forms you should use newer technologies such as ASP.net MVC and EntityFramework or other ORMs.
Update :
after reading your link:
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread-safe.
it is maybe from not sharing the same instance of DB2DataAdapter object. Share it with static modifier between pages and see if it helps.
Sorry for the delay, I don't get much time to work on this. The issue turned out to be related to a static variable that was being overwritten... face palm. I'm sure if I posted all of the code you would have noticed it immediately. Thank you for your time and effort.

How to exit from a method manually?

I have a query which returns a DataSet. After that I check whether records are available or not. If no records available I want to display error message, exit from the process and redirect to another page. Methods available in below the exiting method should not execute.
Here is the code I have so far.
ds = dba.loadEmpInfo(number, searchType, department);
string appNumber = "";
if (ds.Tables[0].Rows.Count > 0)
{
appNumber = ds.Tables[0].Rows[0]["Ref_no"].ToString();
workDS = dba.workExp(appNumber, searchType);
}
else
{
WebMsgBox.Show("No Record relevant to this app number are available");
}
If you want to show Alert message from code behind use below syntax,
ScriptManager.RegisterStartupScript(Control control, Type type,string key, string script,bool addScriptTags);
i.e, in the else part
{
ScriptManager.RegisterStartupScript(this, GetType(), "Alert",
"alert('No Record relevant to this app number are available!');", true);
// Now Re-direct to the next page as you wish
Response.Redirect("yourPage.aspx");
}

i want hide some character from email like Sha***aj#gmail.com [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have developed a application, it is user based application. int this app if user forget his password, then user can reset his password only through his email id and in case if user is not remember his email id which is associated with his account at that time i want retrieve password in a social security numbers like sha***aj#gmail.com. How can i achieve this please help me with this problem that will be appreciated. Thank you.
i have got this code from stak over flow but it is not meet my requirement. It is good for only phone number not for email
public static string GetMaskedEmail(string number)
{
if (String.IsNullOrEmpty(number))
return string.Empty;
if (number.Length <= 12)
return number;
string last12 = number.Substring(number.Length - 12, 12);
var maskedChars = new StringBuilder();
for (int i = 0; i < number.Length - 12; i++)
{
maskedChars.Append(number[i] == '-' ? "-" : "#");
}
return maskedChars + last12;
}
Work is a little slow tonight, so I fired up Xamarin Studio and whipped this up for you. This shouldn't be taken as an example in best coding practices, really not at all.
Though what this will provide is a functioning example, from which you can take and build into your own method and hopefully learn in the process. A great resource for reference, if you get lost at all while reading over any code, is MSDN which if you haven't visited yet I would suggest doing so and bookmarking for future use.
using System;
namespace EmailHash
{
class MainClass
{
public static void Main (string[] args)
{
if (args.Length <= 0)
{
Console.WriteLine ("No values were passed to application.");
return;
}
string email = args[0];
int indexOfAt = email.IndexOf ("#");
if (indexOfAt == -1)
{
Console.WriteLine("Unable to find '#' symbol within email.");
return;
}
int indexStart = 3;
int indexEnd = indexOfAt - 2;
if (indexStart >= indexEnd)
{
Console.WriteLine("Not enough characters in email to mask value.");
return;
}
string hashedEmail = email.Replace(email.Substring(indexStart, indexEnd - indexStart), "***");
Console.WriteLine("Original email: " + email);
Console.WriteLine("Hashed email: " + hashedEmail);
return;
}
}
}

Session variable gets lost after publishing (works on dev machine)

A quick project I've been asked to knock together doesn't need crazy security, so, I've implemented a simple login screen that checks the Username & PW against the db.
User u = new User();
if (u.AuthenticateUser(txtUsername.Text, txtPassword.Text))
Session.Add("UserSeshAuthenticated", true);
Response.Redirect("Dashboard.aspx");
All the other pages share a MasterPage and in the Page_Load event:
if ((Session["UserSeshAuthenticated"] == null) || ((bool)Session["UserSeshAuthenticated"] == false))
{
fw.Write("UserSeshAuthenticated has been lost or something");
string path = HttpContext.Current.Request.Url.AbsolutePath;
Response.Redirect("Login.aspx?retpath=" + path);
}
else
{
lblLoggedInUsername.Text = Session["UserSeshAuthenticated"].ToString();
}
This all works very well on my development machine, but when I've published it to my server, by the time my MasterPage loads, it has lost the session variables.
Can anyone help ?... I'm supposed to have it live this afternoon & I didn't think I'd run into this problem !!!
Any help appreciated. Thanks a lot.
In your login code, you add "UserSeshAuthenticated" to the session, but not the User object. If the function u.AuthenticateUser() adds a copy of itself into the Session, that could be your problem. Try adding that in your result block instead. Like this:
User u = new User();
if (u.AuthenticateUser(txtUsername.Text, txtPassword.Text))
{
Session.Add("UserSeshAuthenticated", true);
Session.Add("oUser", u);
Response.Redirect("Dashboard.aspx");
}

Finding out if a Facebook page is liked by a user. Using the Facebook C# SDK

I'm trying to build a Facebook 'fangate' tab or 'reveal' tab for a Facebook page.
You know how it goes - when a user visits the page, they are shown one bit of content if they haven't yet clicked 'Like' and another once they have.
I'm not a PHP guy so I'm attempting to do this with the Facebook C# SDK (http://facebooksdk.codeplex.com) in Visual Studio 2010. I'm fairly new to .NET too so I'm not doing so well with this!
I have to admit I've been cutting and pasting code from all over the place to get this to work and I think I'm almost there but I'm not getting this error:
Invalid signed request.
Line 82: var DecodedSignedRequest = FacebookSignedRequest.Parse(current, FacebookWebContext.Current.SignedRequest.Data.ToString());
Here's my code:
var settings = ConfigurationManager.GetSection("facebookSettings");
var current = settings as IFacebookApplication;
var DecodedSignedRequest = FacebookSignedRequest.Parse(current, FacebookWebContext.Current.SignedRequest.Data.ToString());
dynamic SignedRequestData = DecodedSignedRequest.Data;
var RawRequestData = (IDictionary<string, object>)SignedRequestData;
string currentFacebookPageID = current.AppId;
bool currentFacebookPageLiked = false;
if (RawRequestData.ContainsKey("page") == true)
{
Facebook.JsonObject RawPageData = (Facebook.JsonObject)RawRequestData["page"];
if (RawPageData.ContainsKey("id") == true)
currentFacebookPageID = (string)RawPageData["id"];
if (RawPageData.ContainsKey("liked") == true)
currentFacebookPageLiked = (bool)RawPageData["liked"];
}
if (currentFacebookPageLiked)
{
//Do some stuff for fans
}
else
{
//Do some stuff for non-fans
}
All the Facebook settings are in my web.config file and I have checked that the AppID and AppSecret are correct.
Can anyone offer me any insight into this issue please? Is there a better way of doing this that I've not yet found?
Many thanks in advance for any help.
OK, I've sorted it out - but I'm not sure why. I have a feeling that the Facebook C# SDK screws around with the signed request in some way. If I get the signed request using Request.Forms["signed_request"] it all seems to work.
I'll share my working code in the hope that it will help others with the same problem.
//Pull in the facebook app settings from the web.config file
var settings = ConfigurationManager.GetSection("facebookSettings");
var current = settings as IFacebookApplication;
//Set up some stuff for later
string currentFacebookPageID = current.AppId;
bool currentFacebookPageLiked = false;
//Get the signed request
FacebookSignedRequest SignedRequest = FacebookSignedRequest.Parse(current, Request.Form["signed_request"]);
dynamic SignedRequestData = SignedRequest.Data;
//extract what we need from the request
var RawRequestData = (IDictionary<string, object>)SignedRequestData;
//Check to see if we've got the data we need
if (RawRequestData.ContainsKey("page") == true)
{
//We do, lets examine it and set the boolean as appropriate
Facebook.JsonObject RawPageData = (Facebook.JsonObject)RawRequestData["page"];
if (RawPageData.ContainsKey("id") == true)
currentFacebookPageID = (string)RawPageData["id"];
if (RawPageData.ContainsKey("liked") == true)
currentFacebookPageLiked = (bool)RawPageData["liked"];
}
if (currentFacebookPageLiked)
{
//Do some stuff for fans
lblName.Text = "Hi " + result.first_name + " - You are a fan";
}
else
{
//Do some stuff for non-fans
lblName.Text = "Hi " + result.first_name + " - please click the like button";
}
This is the code i used and it worked great for me.
protected bool IsPageLiked()
{
var current = ConfigurationManager.GetSection("facebookSettings")
as IFacebookApplication;
dynamic signedRequest = FacebookSignedRequest.Parse(current, Request);
try
{
return signedRequest.Data.page.liked;
}
catch (Exception)
{
return false;
}
}

Categories

Resources