Set Expiry for Offline setup Application - c#

Primarily am new to Developing.
I have Built a Setup File for my c# web Application using VS 2017. Am Going to Deploy my Setup in client Computer with Expiry Date which will be stored in registry. My setup can work in offline. But i want to collect/gather Client data weekly once. So What all i want is , let my client to use my setup without internet for one week. after that my setup have to become expired. Then he/she must connect with internet to extend an expiry date for Next one week. Kindly Help Me to achieve this. Thanks in advance

First of all create new form for read/write/check registry for check registration date and check with current date and add that for main form (first opening form, for this you can change form name in program.cs) , also you can add method in current main form and run that method in load events, after check you can chose between start program or show dialog for connect and extend or etc..
small code :
public partial class Reg_Form : Form
{
private string Reg_path = "Software\\MySampleProgram";
private string Reg_key = "Expire";
public Reg_Form()
{
InitializeComponent();
check_expire_date();
}
private void check_expire_date()
{
bool exists_key = check_reg();
if (!exists_key)
{
//first use, so we need to write expire date
bool is_write = write_reg();
if (!is_write)
{
MessageBox.Show("Run program as administrator and try again.");
this.Close();
}
}
var dt = read_reg_val();
if (dt != null)
{
DateTime current_date = DateTime.UtcNow;
DateTime reg_date = DateTime.UtcNow;
DateTime.TryParse(dt, out reg_date);
var res = (current_date - reg_date).TotalDays;
if (res < 7)
{
Main_Form frm = new Main_Form();
this.Hide();
frm.Show();
}
else
{
MessageBox.Show("Please connect to internet for extend time !");
//do any other work.....
}
}
else
{
MessageBox.Show("Error, try again !");
this.Close();
}
}
private bool write_reg()
{
try
{
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(Reg_path);
key.SetValue(Reg_key, DateTime.UtcNow.ToShortDateString());
key.Close();
return true;
}
catch
{
return false;
}
}
private bool check_reg()
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(Reg_path);
if (key != null)
{
Object o = key.GetValue(Reg_key);
if (o != null)
{
return true;
}
}
}
catch
{
return false;
}
return false;
}
private string read_reg_val()
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(Reg_path);
if (key != null)
{
Object o = key.GetValue(Reg_key);
if (o != null)
{
string res = o as String;
DateTime dt = DateTime.Now;
bool ok_date = DateTime.TryParse(res, out dt);
if (ok_date)
{
return res;
}
else
{
//changed value by user or hacked !
DateTime today = DateTime.UtcNow;
DateTime sevenDaysEarlier = today.AddDays(-8);
return sevenDaysEarlier.ToShortDateString();
}
}
}
}
catch
{
return null;
}
return null;
}
}
Note : this is note perfect, user can change the time & date on PC Or if can find registry can change and bypass expiry date, however it's good sample for you.
if problem solved, so please don't forget to mark answer as accepted/solved.

Related

Elegant way to programmatically check if BitLocker is available on system?

I'm currently working on a installer kind of program. It has a system check page where I check if all the requerments are met or not. One requirement is the availability of BitLocker.
Currently I check for BitLocker by trying to create an instance of Win32_EncryptableVolume and then check if an exception is thrown or not.
But I wonder if there is a more elegant way.
My method currently looks basicaly like this:
public static bool IsBitlockerAvaliable()
{
try
{
var path = new ManagementPath
{
NamespacePath = #"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption",
ClassName = "Win32_EncryptableVolume"
};
using (var wmi_class = new ManagementClass(path))
{
foreach (var o in wmi_class.GetInstances())
{
var vol = (ManagementObject) o;
if (vol == null)
throw new Exception("Vol is null");
Debug.WriteLine(vol);
}
}
return true;
}
catch (ManagementException e)
{
// No Admin rights is a different issue
if (e.ErrorCode == ManagementStatus.AccessDenied)
{
throw new AccessViolationException();
}
return false;
}
catch (Exception e)
{
return false;
}
}

using entityFrameWork in windows service application gives the underlying providor failed to open error

This is my service start code and my class. it is long but problem is just with database and entityFrameWork section please omit other lines. consider I just want to read a data from database:
my service start code:
protected override void OnStart(string[] args)
{
System.Threading.Thread newThread = new System.Threading.Thread(new System.Threading.ThreadStart(ReadPolling.Read));
newThread.Start();
}
this is my ReadPolling.cs file:
public class ReadPolling
{
public static webtccUsersEntities db;
public static void Read()
{
try
{
byte[] readBuffer = new byte[1024];
while (true)
{
writeToDb(readBuffer);
System.IO.File.WriteAllText("D:\\1.txt", "read-write");
}
}
catch (Exception ex)
{
System.IO.File.WriteAllText("D:\\1.txt", ex.Message);
}
}
public static void writeToDb(byte[] userId)
{
db = new webtccUsersEntities();
string _userId="";foreach(byte item in userId)
{
if(item!=0 || item!=40)
_userId += (39 - item).ToString();
}
_userId = "0009544023";
Time time;
if(db.Times.Where(i=>i.userId==_userId).Count()>0)//User has at least one time
{
time = db.Times.Where(i => i.userId == _userId).OrderBy(i => i.dayDate).OrderBy(i=>i.inTime).Last();//last time
if (time.dayDate == DateTime.Today)//today time
{
if(time.outTime==null)//wants an out for today
{
time.outTime = DateTime.Now.ToLocalTime();//an out for today
db.SaveChanges();
}
else//wants a new in/out for today
{
Time newTime = new Time();newTime = db.Times.Create(); newTime.userId = _userId; newTime.dayDate = DateTime.Now.Date; newTime.inTime = DateTime.Now.ToLocalTime();
db.Times.Add(newTime);db.SaveChanges();
}
}
else//not today time
{
//new in for today
Time newTime = new Time();newTime = db.Times.Create();newTime.dayDate = DateTime.Today;newTime.inTime = DateTime.Now.ToLocalTime();newTime.userId = _userId;
db.Times.Add(newTime);db.SaveChanges();
}
}
else//user first time
{
Time firstTime = new Time();
firstTime = db.Times.Create();
firstTime.userId = _userId;firstTime.dayDate = DateTime.Now.Date;firstTime.inTime = DateTime.Now.ToLocalTime();
db.Times.Add(firstTime);db.SaveChanges();
}
}
}
as you can see if an error occurs I write it to a file named "1.txt" in my drive "D:\". so when I start the service i open my text file and see the error "The underlying provider failed on Open.Login failed for user 'NT AUTHORITY\LOCAL SERVICE'.".
what causes the problem?
You should log the inner exception as well as it indicates the actual connectivity error, which could be as simple as an invalid or missing connection string in your .config file...

Add registry key through code

I'm trying to add a registry key through my code on the startup of the program. I'm completely new to this and I don't know how to (and couldn't search for) but I have tried with this code:
RegistryKey HTML5Key = Registry.LocalMachine.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
if (HTML5Key != null)
{
HTML5Key.SetValue("mybrowser.exe", "270f", RegistryValueKind.DWord);
HTML5Key.Close();
}
But it simply does nothing. What am I doing wrong? I have admin rights. I have tried to debug it but I can't even get inside the if bracket.
You use OpenSubKey to open key in registry, so if specified key is not exist in registry it will return null. That is why your code is not working. Check whether sub key exist or not and then open it for writting.
One more mistake in your code you want to open HKEY_CURRENT_USER sub key so write code as follows
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true)
You can use below code for write the value in registry.
private string _subKey = "Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION";
private string SubKey
{
get { return _subKey; }
set { _subKey = value; }
}
private RegistryKey _baseRegistryKey = Registry.LocalMachine;
private RegistryKey BaseRegistryKey
{
get { return _baseRegistryKey; }
set { _baseRegistryKey = value; }
}
private bool WriteDbToRegistry(string keyName, object value)
{
try
{
var rk = BaseRegistryKey;
var sk1 = rk.CreateSubKey(SubKey);
if(sk1 != null) sk1.SetValue(keyName.ToUpper(), value);
return true;
}
catch(Exception e)
{
MessageBox.Show("Please run your App as Administrator.", "Administrator");
return false;
}
}
bool results = WriteDbToRegistry("Keyname", "2710");
and get value from registry..
public string GetRegistryValue()
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey);
try
{
return (string)sk1.GetValue("Keyname");
}
catch (Exception e)
{
MessageBox.Show(e.Message, "some message");
return null;
}
}
I put this together with minor changes to the code previously given by JasRaj to create the registry entry:
private string _subKey = "SOFTWARE\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION";
private string SubKey
{
get { return _subKey; }
set { _subKey = value; }
}
private RegistryKey _baseRegistryKey = Registry.LocalMachine;
private RegistryKey BaseRegistryKey
{
get { return _baseRegistryKey; }
set { _baseRegistryKey = value; }
}
private bool WriteDbToRegistry(string keyName, object value)
{
try
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey,true); //true is required for making it writable
if (sk1 != null)
{
sk1.SetValue(keyName, value,RegistryValueKind.DWord); //dword,qword
rk.Close();
sk1.Close();
return true;
}
else
{
rk.Close();
sk1.Close();
return false;
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
return false;
}
}
public string GetRegistryValue(string keyname)
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey);
try
{
return sk1.GetValue(keyname).ToString();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error");
return null;
}
}
There are two problems with your code:
You likely don't have permissions to write to HKEY_LOCAL_MACHINE
You are not writing to the right location and an invalid value is used
Your problem is that you are writing to HKEY_LOCAL_MACHINE and you most likely don't have permissions to write there under a normal user account. Unless you are an Administrator and running under elevated rights you can't write there. However, for what you are trying to do luckily you don't need to write the HKLM, but you can write to the HKCU registry which is allowed.
Also the "270F" should be a number not a string so 0x270F without quotes should be used.
The following code is what I use in one of my applications to set browser emulation:
using (var rk = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",true))
{
dynamic value = rk.GetValue("MarkdownMonster.exe");
if (value == null)
rk.SetValue(exename, (uint) 11001, RegistryValueKind.DWord);
}

Login using WCF service application on a asp.net web application

I'm currently developing a dating site for a school project, and I'mm currently trying to make a log in feature for it. We are not supposed to use the automatic register and login feature.
Any contact we have with the database should go through the WCF service application. I know how to implement it without using the WCF, but I need to use it now, and I can't find this on Google after searching .
public bool login(string UserName, string PassWord, bool isActive = true) {
try {
DALDataContext db = new DALDataContext();
var qry = from m in db.tblUsers
where m.userName == UserName && m.password == PassWord && m.isActive == isActive
select m;
if (qry.Count() > 0) {
return true;
} else {
return false;
}
}
catch (Exception) {
return false;
}
}
That's how I made it, so this should work if I implement it in my web application
like this:
ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
protected void btnLoginUser_Click1(object sender, EventArgs e) {
try {
string UserName = txtUserName.Text;
string PassWord = txtPassWord.Text;
obj.login(UserName, PassWord);
if (true) {
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
}
}
catch (Exception){
}
}
I've been working with this for hours, the register part of this works... so I'm doing something really wrong or something. I'm using Visual Studio 2010 and SQL Server 2008 R2.
[SOLVED]
this is how i solved it
protected void btnLoginUser_Click1(object sender, EventArgs e)
{
try
{
string UserName = txtUserName.Text;
string PassWord = txtPassWord.Text;
bool isActive = true;
if (obj.login(UserName, PassWord, isActive))
{
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
}
else
{
lblErr.Text = "fail";
}
}
catch (Exception)
{
}
}
}
}
You are ignoring the return value of your login method:
obj.login(UserName, PassWord); // <-- returns true/false.
if (true) // <-- Why?
{
...
Did you mean to do
if (obj.login(UserName, PassWord))
{
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
} ...
Suggest to return user from WCF service by name, like:
public tblUser login(string UserName);
In the client side you can retrieve user by name:
var user = obj.login(UserName);
if (user != null && user.password == txtPassWord.Text)
DoLogin();
else
ShowError();

facebook desktop app C#

I am trying to build a desktop app to use facebook api and get data from friends.
Anyways I am stuck in the log in stage.
I have used some advice and made the log in to facebook with WebBrowser. It works great.
I am stuck at trying to make it give me status = Failed or success
I tried doing it like this at the end of the button_1 method
if (!w.DocumentText.Contains(#"<div class=""linkWrap noCount"">Messages</div>"))
{
w.Navigate(#"http://www.facebook.com/login.php");
MessageBox.Show("Login error. Wrong username or password!");
}
else
{
MessageBox.Show("Logged in successfully");
}
the < div class=""linkWrap noCount"">Messages< /div> is only shown while logged in so thats why I use it to see if a user is logged in
but the problem is it always gives me an error (wrong user and pass) becasue it reads it before the browser finishes to navigate to the page. I tried threads and thread sleep and even timers but it doesnt seem to work
an ideas?
here is the code:
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();
string email = textBox1.Text;
string password = textBox2.Text;
// create a new browser
WebBrowser w = new WebBrowser();
w.Dock = DockStyle.Fill;
this.Controls.Add(w); // you may add the controll to your windows forms if you want to see what is going on
// latter you may not chose to add the browser or you can even set it to invisible...
// navigate to facebook
w.Navigate(#"http://www.facebook.com/login.php");
// wait a little
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
HtmlElement temp=null;
// while we find an element by id named email
while (temp == null)
{
temp = w.Document.GetElementById("email");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once we find it place the value
temp.SetAttribute("value", email);
temp = null;
// wiat till element with id pass exists
while (temp == null)
{
temp = w.Document.GetElementById("pass");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once it exist set its value equal to passowrd
temp.SetAttribute("value", password);
// if you already found the last fields the button should also be there...
var inputs = w.Document.GetElementsByTagName("input");
int counter = 0;
bool enableClick = false;
// iterate through all the inputs in the document
foreach (HtmlElement btn in inputs)
{
try
{
var att = btn.GetAttribute("tabindex");
var name = btn.GetAttribute("id");
if (enableClick)// button to submit always has a differnt id. it should be after password textbox
{
btn.InvokeMember("click");
counter++;
}
if (name.ToUpper().Contains("PASS") || att=="4")
{
enableClick = true; // button should be next to the password input
}
// try a max of 5 times
if (counter > 5)
{
break;
}
}
catch
{
}
}
}
Checkout the facebook-sharp SDK for Windows forms:
https://github.com/facebook-csharp-sdk/facebook-winforms
I recommend you use Facebook C# SDK. It uses the OAuth protocol, for user-authentication.
Down an code example how to get user friends with Facebook-C#-SDK:
using Facebook; //add reference to facebook dll for it work
declare the fields:
private FacebookOAuthResult result;
private FacebookOAuthClient OAuth;
and
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Url.AbsolutePath == "/login.php")
{
// do login..
}
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
FacebookClient fbClient = new FacebookClient(result.AccessToken);
dynamic friends = fbClient.Get("/me/friends"); //User friends
// do something..
}
else
{
string errorDescription = result.ErrorDescription;
string errorReason = result.ErrorReason;
string msg = String.Format("{0} ({1})", errorReason, errorDescription);
MessageBox.Show(msg, "User-authentication failed!");
}
}
}
and then for start user-authentication:
//..
OAuth = new FacebookOAuthClient();
OAuth.AppId = appId; // see link above,you can find how to get it
OAuth.AppSecret = appSecret; // see link above,you can find how to get it
Uri loginUrl = OAuth.GetLoginUrl(paramenters);
webBrowser1.Navigate(loginUrl.AbsoluteUri);

Categories