0byt3m1n1
Path:
C:
/
BACKUPS
/
Biometric Backup
/
KELTRON
/
COSEC V14R4.1
/
Setup
/
API Samples
/
CSharp
/
Backup
/
[
Home
]
File: apiHelper.cs
using System; using System.Globalization; using System.Data; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Net; using System.IO; using System.Threading; namespace Cosec { public class apiHelper { public enum DataFormat { Text, XML, } public enum DeviceListOption { All, Panel, Door, Group } public enum HTTPOperation { Request, Response, Error } private const string strORGCode = "ORG"; private const string strBRCCode = "BRC"; private const string strDPTCode = "DPT"; private const string strDSGCode = "DSG"; private const string strSECCode = "SEC"; private const string strCTGCode = "CTG"; private const string strGRDCode = "GRD"; private const string strUserCode = "USR"; // changed for group alias private static string _strORG = "Organization"; public static string strORG { get { return _strORG; } } private static string _strBRC = "Branch"; public static string strBRC { get { return _strBRC; } } private static string _strDPT = "Department"; public static string strDPT { get { return _strDPT; } } private static string _strSEC = "Section"; public static string strSEC { get { return _strSEC; } } private static string _strGRD = "Grade"; public static string strGRD { get { return _strGRD; } } private static string _strCTG = "Category"; public static string strCTG { get { return _strCTG; } } private static string _strDSG = "Designation"; public static string strDSG { get { return _strDSG; } } private static string _strUser = "User"; public static string strUser { get { return _strUser; } } // public delegate void HttpOperationsHandler(HTTPOperation operation, string data); public static event HttpOperationsHandler HttpOperations; static apiHelper() { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB", false); } public class UserAPIParameters { public string id = ""; public string reference_code = ""; public string name = ""; public string short_name = ""; public string active = ""; public string date_of_birth = ""; public string official_phone = ""; public string official_extension = ""; public string official_cell = ""; public string official_email = ""; public string pin = ""; public string card_1 = ""; public string card_2 = ""; public string access_validity_date = ""; public string organization = ""; public string branch = ""; public string department = ""; public string designation = ""; public string section = ""; public string category = ""; public string grade = ""; /// <summary> /// This field will not be applicable for Set User. /// This is basically to get list of device assign to specific user. /// To assign or revoke device for user Use device?action=assign or device?action=revoke /// </summary> public List<string> device = new List<string>(); /// <summary> /// Use this method before save data. to validate fields. /// </summary> /// <returns>true = all fields are validated</returns> public bool ValidateFields() { try { if(string.IsNullOrEmpty(id) == true || IsValidDecimal(id) == false) throw new Exception("Invalid id=" + id); else if(Convert.ToDecimal(id) <= 0 || Convert.ToDecimal(id) > 99999999) throw new Exception("Invalid id=" + id); if(string.IsNullOrEmpty(reference_code) == true || IsVldAlphaNumeric(reference_code) == false) throw new Exception("Invalid reference-code=" + reference_code); if (string.IsNullOrEmpty(name) == true) throw new Exception("Invalid name=" + name); if (string.IsNullOrEmpty(short_name) == true) throw new Exception("Invalid short-name=" + short_name); if (string.IsNullOrEmpty(date_of_birth) == false) { string convertedDate = ConvertToDateFormat(date_of_birth); if (!IsDate(convertedDate ) || Convert.ToDateTime(convertedDate ) >= DateTime.Now.Date) throw new Exception("Invalid command date-of-birth=" + convertedDate); } if (string.IsNullOrEmpty(official_phone) == false) { if (!IsVldPhNo(official_phone)) throw new Exception("Invalid command official-phone=" + official_phone); } if (string.IsNullOrEmpty(official_extension) == false) { if (!IsNumeric(official_extension)) throw new Exception("Invalid command official-extension=" + official_extension); } if (string.IsNullOrEmpty(official_cell) == false) { if (!IsVldPhNo(official_cell)) throw new Exception("Invalid command official-cell=" + official_cell); } if (string.IsNullOrEmpty(official_email) == false) { if (!Regex.IsMatch(official_email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")) throw new Exception("Invalid command official-email=" + official_email); } if (string.IsNullOrEmpty(pin) == false) { if (!IsNumeric(pin)) throw new Exception("Invalid command pin=" + pin); } if (string.IsNullOrEmpty(card_1) == false) { if (!IsValidDecimal(card_1)) throw new Exception("Invalid command card-1=" + card_1); else if (Convert.ToDecimal(card_1) > Convert.ToDecimal("99999999999999999999")) throw new Exception("Invalid command card-1=" + card_1); } if (string.IsNullOrEmpty(card_2) == false) { if (!IsValidDecimal(card_2)) throw new Exception("Invalid command card-2=" + card_2); else if (Convert.ToDecimal(card_2) > Convert.ToDecimal("99999999999999999999")) throw new Exception("Invalid command card-2=" + card_2); } if (string.IsNullOrEmpty(card_1) == false && string.IsNullOrEmpty(card_2) == false) { if (card_1 != "0" && card_2 != "0") { if (Convert.ToDecimal(card_1) == Convert.ToDecimal(card_2)) throw new Exception("Invalid command card-1 or card-2 should not be the same"); } } if (!string.IsNullOrEmpty(access_validity_date)) { string convertedDate = ConvertToDateFormat(access_validity_date); if (!IsDate(convertedDate)) throw new Exception("Invalid command access-validity-date=" + convertedDate); } return true; } catch (Exception ex) { throw ex; } } } public class APIResponse { public string data; public DataFormat dataFormat; public bool isSuccess; public string successFailMessage; public Stream dataStream { get { if (string.IsNullOrEmpty(data)) return null; else { if (dataFormat == DataFormat.XML) return new MemoryStream(Encoding.UTF8.GetBytes(data)); else return new MemoryStream(Encoding.Default.GetBytes(data)); } } } } private static string _baseAddress; public static string BaseAddress { get { return _baseAddress; } set { _baseAddress = value; } } public static string LoginID; public static string Password; private static APIResponse HTTPRequest(string url) { apiHelper.APIResponse objResponse = new apiHelper.APIResponse(); try { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_baseAddress + "/" + url); CredentialCache credCache = new CredentialCache(); credCache.Add(request.RequestUri, "BASIC", new NetworkCredential(LoginID, Password)); if (HttpOperations != null) HttpOperations(HTTPOperation.Request, _baseAddress + "/" + url); //request.Credentials = CredentialCache.DefaultCredentials; request.Credentials = credCache; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream receiveStream = response.GetResponseStream(); StreamReader rd = new StreamReader(receiveStream, Encoding.UTF8); objResponse.data = rd.ReadToEnd(); if (HttpOperations != null) HttpOperations(HTTPOperation.Response, objResponse.data); response.Close(); receiveStream.Close(); rd.Close(); } catch (Exception ex) { objResponse.data = "failed: " + ex.Message; if (HttpOperations != null) HttpOperations(HTTPOperation.Error, ex.Message); } if (string.IsNullOrEmpty(objResponse.data) == false) { if (objResponse.data.StartsWith("success:") || objResponse.data.StartsWith("failed:")) { if (objResponse.data.StartsWith("success:")) objResponse.isSuccess = true; string msg = objResponse.data.Substring(objResponse.data.IndexOf(":") + 1 ); objResponse.successFailMessage = msg.Trim(); objResponse.data = ""; } else if (objResponse.data.StartsWith("<?xml") || objResponse.data.StartsWith("<NewDataSet") || objResponse.data.StartsWith("<Document")) { objResponse.isSuccess = true; objResponse.dataFormat = DataFormat.XML; } else { objResponse.isSuccess = true; objResponse.dataFormat = DataFormat.Text; } } } catch (Exception ex) { throw ex; } return objResponse; } private static APIResponse sendRequest(string url) { apiHelper.APIResponse objResponse = null; try { objResponse = HTTPRequest(url); } catch (Exception ex) { throw ex; } return objResponse; } /// <summary> /// This function will check API Service is accessible and provided LoginID and Password is correct or not. /// </summary> /// <param name="error"></param> /// <returns>Return True if API Service is accessible and LoginID and Password is correct else it will return false.</returns> public static bool Ping(out string error) { error = ""; APIResponse response = sendRequest(""); if (response.isSuccess == false) { error = response.successFailMessage; return false; } else { APIResponse apiResponse = GetGroupNameList(DataFormat.XML); if (apiResponse != null) { if (string.IsNullOrEmpty(apiResponse.data) == false) { DataSet ds = new DataSet(); ds.ReadXml(apiResponse.dataStream); if (ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string strcode = ds.Tables[0].Rows[i]["code"].ToString(); switch (strcode.ToUpper()) { case strORGCode: { _strORG = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } case strBRCCode: { _strBRC = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } case strDPTCode: { _strDPT = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } case strSECCode: { _strSEC = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } case strGRDCode: { _strGRD = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } case strDSGCode: { _strDSG = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } case strCTGCode: { _strCTG = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } case strUserCode: { _strUser = ds.Tables[0].Rows[i]["aliasName"].ToString(); break; } } } } } } return true; } } #region User set/get public static APIResponse SaveUser(UserAPIParameters objUserParam) { try { if(objUserParam.ValidateFields()) { string actionURL = strUser + "?action=set"; actionURL += ";id=" + objUserParam.id; if(string.IsNullOrEmpty(objUserParam.reference_code) == false) actionURL += ";reference-code=" + objUserParam.reference_code; actionURL += ";name=" + objUserParam.name; if (string.IsNullOrEmpty(objUserParam.short_name) == false) actionURL += ";short-name=" + objUserParam.short_name; if (string.IsNullOrEmpty(objUserParam.active) == false) actionURL += ";active=" + objUserParam.active; if (string.IsNullOrEmpty(objUserParam.date_of_birth) == false) actionURL += ";date-of-birth=" + objUserParam.date_of_birth; if (string.IsNullOrEmpty(objUserParam.official_phone) == false) actionURL += ";official-phone=" + objUserParam.official_phone; if (string.IsNullOrEmpty(objUserParam.official_extension) == false) actionURL += ";official-extension=" + objUserParam.official_extension; if (string.IsNullOrEmpty(objUserParam.official_cell) == false) actionURL += ";official-cell=" + objUserParam.official_cell; if (string.IsNullOrEmpty(objUserParam.official_email) == false) actionURL += ";official-email=" + objUserParam.official_email; if (string.IsNullOrEmpty(objUserParam.pin) == false) actionURL += ";pin=" + objUserParam.pin; if (string.IsNullOrEmpty(objUserParam.card_1) == false) { if (objUserParam.card_1 == "0") actionURL += ";card-1="; else actionURL += ";card-1=" + objUserParam.card_1; } if (string.IsNullOrEmpty(objUserParam.card_2) == false) { if (objUserParam.card_2 == "0") actionURL += ";card-2="; else actionURL += ";card-2=" + objUserParam.card_2; } if(string.IsNullOrEmpty(objUserParam.access_validity_date) == false) actionURL += ";access-validity-date=" + objUserParam.access_validity_date; if (!string.IsNullOrEmpty(objUserParam.organization)) actionURL += ";" + strORG + "=" + objUserParam.organization; if (!string.IsNullOrEmpty(objUserParam.branch)) actionURL += ";" + strBRC + "=" + objUserParam.branch; if (!string.IsNullOrEmpty(objUserParam.department)) actionURL += ";" + strDPT + "=" + objUserParam.department; if (!string.IsNullOrEmpty(objUserParam.designation)) actionURL += ";" + strDSG + "=" + objUserParam.designation; if (!string.IsNullOrEmpty(objUserParam.section)) actionURL += ";" + strSEC + "=" + objUserParam.section; if (!string.IsNullOrEmpty(objUserParam.category)) actionURL += ";" + strCTG + "=" + objUserParam.category; if (!string.IsNullOrEmpty(objUserParam.grade)) actionURL += ";" + strGRD + "=" + objUserParam.grade; return sendRequest(actionURL); } return null; } catch(Exception ex) { throw ex; } } public static apiHelper.UserAPIParameters GetUser(string UserID, out string err) { err = ""; string actionURL = strUser + "?action=get;id=" + UserID + ";format=xml"; APIResponse resultData = sendRequest(actionURL); apiHelper.UserAPIParameters objUserAPIParam = null; if(resultData.dataFormat == DataFormat.XML) { try { DataSet ds = new DataSet(); ds.ReadXml(resultData.dataStream); DataTable dtUser = ds.Tables[0]; if(dtUser.Rows.Count > 0) { objUserAPIParam = new apiHelper.UserAPIParameters(); objUserAPIParam.id = Convert.ToString(dtUser.Rows[0]["id"]); objUserAPIParam.reference_code = Convert.ToString(dtUser.Rows[0]["reference-code"]); objUserAPIParam.name = Convert.ToString(dtUser.Rows[0]["name"]); objUserAPIParam.short_name = Convert.ToString(dtUser.Rows[0]["short-name"]); objUserAPIParam.active = Convert.ToString(dtUser.Rows[0]["active"]); objUserAPIParam.date_of_birth = Convert.ToString(dtUser.Rows[0]["date-of-birth"]); objUserAPIParam.official_phone = Convert.ToString(dtUser.Rows[0]["official-phone"]); objUserAPIParam.official_extension = Convert.ToString(dtUser.Rows[0]["official-extension"]); objUserAPIParam.official_cell = Convert.ToString(dtUser.Rows[0]["official-cell"]); objUserAPIParam.official_email = Convert.ToString(dtUser.Rows[0]["official-email"]); objUserAPIParam.pin = Convert.ToString(dtUser.Rows[0]["pin"]); objUserAPIParam.card_1 = Convert.ToString(dtUser.Rows[0]["card-1"]); objUserAPIParam.card_2 = Convert.ToString(dtUser.Rows[0]["card-2"]); objUserAPIParam.access_validity_date = Convert.ToString(dtUser.Rows[0]["access-validity-date"]); objUserAPIParam.organization = Convert.ToString(dtUser.Rows[0][strORG]); objUserAPIParam.branch = Convert.ToString(dtUser.Rows[0][strBRC]); objUserAPIParam.department = Convert.ToString(dtUser.Rows[0][strDPT]); objUserAPIParam.designation = Convert.ToString(dtUser.Rows[0][strDSG]); objUserAPIParam.section = Convert.ToString(dtUser.Rows[0][strSEC]); objUserAPIParam.category = Convert.ToString(dtUser.Rows[0][strCTG]); objUserAPIParam.grade = Convert.ToString(dtUser.Rows[0][strGRD]); string devices = Convert.ToString(dtUser.Rows[0]["device"]); objUserAPIParam.device.Clear(); if(string.IsNullOrEmpty(devices) == false) { string[] mstr = devices.Split(','); foreach(String str in mstr) { if (!string.IsNullOrEmpty(str.Trim())) objUserAPIParam.device.Add(str.Trim()); } } } dtUser.Dispose(); dtUser = null; } catch(Exception ex) { throw ex; } } else { err = resultData.successFailMessage; return null; } return objUserAPIParam; } #endregion #region Data get public static APIResponse GetEventACS(decimal index, decimal count, apiHelper.DataFormat format) { string actionURL = "event-acs?action=get;index=" + index.ToString() + ";count=" + count.ToString()+";format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetEventTA(decimal index, decimal count, apiHelper.DataFormat format) { string actionURL = "event-ta?action=get;index=" + index.ToString() + ";count=" + count.ToString()+";format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetAttendanceDaily(string fromDate,string toDate,string range, string id, apiHelper.DataFormat format) { string actionURL = ""; if(range.ToLower().Trim() != "all") actionURL = "attendance-daily?action=get;date-range=" + fromDate + "-" + toDate + ";range=" + range + ";id=" + id + ";format=" + format.ToString().ToLower(); else actionURL = "attendance-daily?action=get;date-range=" + fromDate + "-" + toDate + ";range=" + range + ";format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetAttendanceMonthly(int month,int year,string range, string id, apiHelper.DataFormat format) { string actionURL = ""; if(range.ToLower().Trim() != "all") actionURL = "attendance-monthly?action=get;month-year=" + month.ToString("0#") + year.ToString("000#") + ";range=" + range + ";id=" + id + ";format=" + format.ToString().ToLower(); else actionURL = "attendance-monthly?action=get;month-year=" + month.ToString("0#") + year.ToString("000#") + ";range=" + range + ";format=" + format.ToString().ToLower(); return sendRequest(actionURL); } #endregion #region Group get public static APIResponse GetGroupNameList(apiHelper.DataFormat format) { string actionURL = "group-rename-list?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetOrganization(apiHelper.DataFormat format) { string actionURL = strORG + "?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetBranch(apiHelper.DataFormat format) { string actionURL = strBRC + "?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetDepartment(apiHelper.DataFormat format) { string actionURL = strDPT + "?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetDesignation(apiHelper.DataFormat format) { string actionURL = strDSG + "?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetSection(apiHelper.DataFormat format) { string actionURL = strSEC + "?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetCategory(apiHelper.DataFormat format) { string actionURL = strCTG + "?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } public static APIResponse GetGrade(apiHelper.DataFormat format) { string actionURL = strGRD + "?action=get;format=" + format.ToString().ToLower(); return sendRequest(actionURL); } #endregion #region Device get/assign/revoke /// <summary> /// This will give list of devices and device groups /// p_* indicates that device type is panel. /// d_* indicates that device type is door. /// g_* indicates that group of panel and door. /// </summary> /// <param name="listOption">specify which type of list you want</param> /// <param name="format">xml or text</param> /// <returns>return the list of devices and groups</returns> public static APIResponse GetDevice(DeviceListOption listOption, apiHelper.DataFormat format) { string actionURL = "device?action=get;type=" + listOption.ToString().ToLower() + ";format=" + format.ToString().ToLower(); return sendRequest(actionURL); } /// <summary> /// To assign device(s) to user(s). before assign or revoke devices use GetDevice to find avaiable device and device group list in the system. /// </summary> /// <param name="device">you can provide range of devices or single device</param> /// <param name="id">you can provide range of user ids.</param> /// <returns>Return success or failed</returns> public static APIResponse AssignDevice(string device, string id) { string actionURL = "device?action=assign;device=" + device + ";id=" + id; return sendRequest(actionURL); } /// <summary> /// To remove device(s) from specified user(s). before remove devices use GetDevice to find avaiable device and device group list in the system. /// </summary> /// <param name="device">you can provide range of devices or single device</param> /// <param name="id">you can provide range of user ids.</param> /// <returns>Return success or failed</returns> public static APIResponse RevokeDevice(string device, string id) { string actionURL = "device?action=revoke;device=" + device + ";id=" + id; return sendRequest(actionURL); } #endregion #region Validation Methods private static bool IsDate(string Expression) { if (Expression.Trim() == string.Empty) { return true; } if (Expression.Trim().Length != 10) { return false; } if (Expression.Trim().Substring(2, 1) != "/" || Expression.Trim().Substring(5, 1) != "/") { return false; } bool isDt; DateTime retDt; DateTimeFormatInfo myDTFI = new CultureInfo("en-GB", false).DateTimeFormat; isDt = DateTime.TryParse(Expression, myDTFI, System.Globalization.DateTimeStyles.None, out retDt); if (isDt) { if (retDt.Year < 1900 || retDt.Year > 2099) { isDt = false; } } return isDt; } private static bool IsVldPhNo(string Expression) { if (Expression.Trim() == string.Empty) { return true; } string strVld = "1234567890-()+"; bool isVld = false; string strVldSub; for (int i = 0; i < Expression.Length; i++) { strVldSub = Expression.Substring(i, 1); if (strVld.Contains(strVldSub)) { isVld = true; } else { isVld = false; return false; } } return isVld; } private static bool IsNumeric(string Expression) { if (Expression.Trim() == string.Empty) { return true; } bool isNum; uint retNum; isNum = uint.TryParse(Expression, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); return isNum; } private static bool IsValidDecimal(string Expression) { if (Expression.Trim() == string.Empty) { return true; } bool isNum; decimal retNum; isNum = decimal.TryParse(Expression, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); return isNum; } private static bool IsVldAlphaNumeric(string Expression) { if (Expression.Trim() == string.Empty) { return true; } string strVld = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; bool isVld = false; string strVldSub; for (int i = 0; i < Expression.Length; i++) { strVldSub = Expression.Substring(i, 1); if (strVld.Contains(strVldSub)) { isVld = true; } else { isVld = false; return false; } } return isVld; } private static string ConvertToDateFormat(string dtValue) { if (string.IsNullOrEmpty(dtValue.Trim()) == true) return ""; string retValue = ""; string dd = ""; string mm = ""; string yyyy = ""; if(dtValue.Length >= 2) dd = dtValue.Substring(0,2); if(dtValue.Length >= 4) mm = dtValue.Substring(2,2); if(dtValue.Length >= 6) { if (dtValue.Length >= 8) yyyy = dtValue.Substring(4, 4); else { yyyy = dtValue.Substring(4, 2); if (yyyy.Length == 2) yyyy = DateTime.Now.Year.ToString().Substring(0, 2) + yyyy; } } retValue = dd + "/" + mm + "/" + yyyy; return retValue; } #endregion } }