using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Sockets; using System.Web; using System.Web.Security; using System.Diagnostics; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace APITester { class VizSeekAPIExample { static void Main(string[] args) { if (args.Length < 12) { Console.WriteLine("One or more parameters are missing."); Console.WriteLine("Parameters:"); Console.WriteLine("-server (VizSeek server address, options: 'https://www.vizseek.com/API' or " + "'https://testsvr.vizseek.com/API')"); Console.WriteLine("-email"); Console.WriteLine("-password"); Console.WriteLine("-clientId"); Console.WriteLine("-file (path of a file to upload to your company database or use for search)"); Console.WriteLine("-isSearchOrAddToDB (0=addToDB, 1=search)"); Console.WriteLine("-attributes (Optional, format = \"name1=value1,name2=value2\")"); Console.WriteLine("-useLocalIndexing ('Y' or 'N', You must have the VizSeek local indexer " + "(available for download on the API tutorial page) installed to use local indexing)"); Console.WriteLine("-jarPath (If using local indexing, this is the path of ZeroMQClient.jar (available for download on the API tutorial page))"); return; } string server = ""; string email = ""; string password = ""; string clientId = ""; string filePath = ""; int isSearchOrAddToDB = 0; string attributes = ""; bool useLocalIndexing = false; string jarPath = ""; for (int i = 0; i < args.Length; i++) { switch (args[i]) { case "-server": i++; server = args[i]; break; case "-email": i++; email = args[i]; break; case "-password": i++; password = FormsAuthentication.HashPasswordForStoringInConfigFile(args[i], "sha1"); break; case "-clientId": i++; clientId = args[i]; break; case "-file": i++; filePath = args[i]; break; case "-isSearchOrAddToDB": i++; isSearchOrAddToDB = Int32.Parse(args[i]); break; case "-attributes": i++; attributes = args[i]; break; case "-useLocalIndexing": i++; useLocalIndexing = args[i].ToString().ToLower() == "y"; break; case "-jarPath": i++; jarPath = args[i]; break; } } using (var client = new HttpClient()) { #region Setup if (server.EndsWith("/")) { server = server.Substring(0, server.Length - 1); } client.BaseAddress = new Uri(server); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json")); #endregion string userAccessToken = null; string userRefreshToken = null; HttpResponseMessage response = null; DateTime expires = new DateTime(); Console.WriteLine("Authenticating..."); var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair("grant_type", "password"), new KeyValuePair("username", email), new KeyValuePair("password", password), new KeyValuePair("client_id", clientId) }); response = client.PostAsync("token", formContent).Result; if (!response.IsSuccessStatusCode) { Console.WriteLine("Authentication failed. Possible incorrect user email, password, client ID, or server address."); } else { Console.WriteLine("Authentication passed."); //get access token from response body var responseJson = response.Content.ReadAsStringAsync().Result; var jObject = JObject.Parse(responseJson); userAccessToken = jObject.GetValue("access_token").ToString(); userRefreshToken = jObject.GetValue("refresh_token").ToString(); expires = DateTime.UtcNow.AddSeconds((double)Int32.Parse(jObject.GetValue("expires_in").ToString())); } if (userAccessToken != null) { //set token client.DefaultRequestHeaders.Add("Authorization", "Bearer " + userAccessToken); //check if a refresh token is needed (user and app access tokens expire after 30 minutes, refresh tokens last 2 weeks) if (expires <= DateTime.UtcNow) { userAccessToken = getRefreshToken(client, userRefreshToken, clientId, out userRefreshToken, out expires); } //first, we will find the company ID, using the User GET API string companyID = null; response = client.GetAsync(string.Format("User?emailID={0}&password={1}", email, password)).Result; if (response.IsSuccessStatusCode) { UserProfile user = response.Content.ReadAsAsync().Result; if (user != null) { companyID = user.CompanyVizSpaceID; } } else { Console.WriteLine("User GET failed. " + response.StatusCode); } if (companyID != null) { string fileName = ""; string extension = ""; string fileContent = ""; if (filePath != "") { if (isSearchOrAddToDB == 0) { if (useLocalIndexing) { filePath = indexLocally(jarPath, filePath); } fileName = Path.GetFileName(filePath); extension = Path.GetExtension(fileName).ToLower(); fileContent = Convert.ToBase64String(File.ReadAllBytes(filePath)); //add a file to the company database. //Note: isSearchInput's default value is true; //Note: attributes are optional string attrs = ""; if (attributes != "") { attrs = "&attributes=" + HttpUtility.UrlEncode(attributes.Replace(',', '&')); } response = client.PutAsJsonAsync("File?file=" + fileName + "&isSearchInput=false" + attrs, JsonConvert.SerializeObject(fileContent)).Result; string fileId = null; if (response.IsSuccessStatusCode) { fileId = response.Content.ReadAsAsync().Result; Console.WriteLine("File upload was successful. The new file ID is: " + fileId); } if (!response.IsSuccessStatusCode || fileId == null) { Console.WriteLine("File upload failed."); } } else if (isSearchOrAddToDB == 1) { string[] byteArrays = new string[1]; if (useLocalIndexing) { filePath = indexLocally(jarPath, filePath); } byteArrays[0] = Convert.ToBase64String(File.ReadAllBytes(filePath)); fileName = Path.GetFileName(filePath); extension = Path.GetExtension(fileName).ToLower(); string fileType = "3D"; if (extension == ".png" || extension == ".jpg" || extension == ".jpeg") { fileType = "image"; } else if (extension == ".dwg" || extension == ".dxf") { fileType = "2D"; } string filterStr = HttpUtility.UrlEncode("uid=" + companyID + "&fileType=" + fileType); response = client.PutAsJsonAsync("Search?searchTypeStr=file&fileExtension=" + Path.GetExtension(fileName) + "&filterStr=" + filterStr, JsonConvert.SerializeObject(byteArrays)).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Search was successful."); SearchResultSummary result = response.Content.ReadAsAsync().Result; if (result != null) { Console.WriteLine(result.ResultsList.Count + " results)"); } else { Console.WriteLine("no results"); } } else { Console.WriteLine("Search failed."); } } } } } } } static string getRefreshToken(HttpClient client, string userRefreshToken, string client_id, out string newRefreshToken, out DateTime tokenExpiration) { newRefreshToken = null; tokenExpiration = DateTime.MinValue; var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair("grant_type", "refresh_token"), new KeyValuePair("refresh_token", userRefreshToken), new KeyValuePair("client_id", client_id) }); Console.WriteLine("Getting refresh user token."); HttpResponseMessage response = client.PostAsync("token", formContent).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Get refresh token successful."); var responseJson = response.Content.ReadAsStringAsync().Result; var jObject = JObject.Parse(responseJson); newRefreshToken = jObject.GetValue("refresh_token").ToString(); tokenExpiration = DateTime.UtcNow.AddSeconds((double)Int32.Parse(jObject.GetValue("expires_in").ToString())); return jObject.GetValue("access_token").ToString(); } else { Console.WriteLine("Get refresh token failed."); return null; } } static string indexLocally(string jarPath, string inputFile) { //this function will create a .ifz file in the location of the original file string ipAddress = null; var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { ipAddress = ip.ToString(); } } if (ipAddress == null) throw new Exception("Local IP Address Not Found!"); string inputFileLocation = Path.GetDirectoryName(inputFile) + "\\"; Process clientProcess = new Process(); clientProcess.StartInfo.FileName = "java"; clientProcess.StartInfo.UseShellExecute = false; clientProcess.StartInfo.Arguments = "-cp " + jarPath + " guide.mdclient tcp://" + ipAddress + ":6555 " + inputFile + " " + inputFileLocation; Console.Write("Starting local indexer..."); clientProcess.Start(); clientProcess.WaitForExit(); int code = clientProcess.ExitCode; Console.Write(code.ToString()); return inputFileLocation + "\\" + Path.GetFileName(inputFile) + ".ifz"; } } public partial class UserProfile { public string CompanyURL { get; set; } public string CompanyVizSpaceID { get; set; } public int CompanyContentType { get; set; } public string VizSpaceID { get; set; } public string CompanyName { get; set; } public string CompanyLogoURL { get; set; } public string EmailID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string ContinueURL { get; set; } public string ICode { get; set; } } public partial class SearchResultSummary { public List ResultsList { get; set; } public int TotalResults { get; set; } public TimeSpan SearchTime { get; set; } public List SearchFilters { get; set; } public List Categories { get; set; } public ProductCategory CurrentCategory { get; set; } public List AdditionalCategories { get; set; } public double InputVolume { get; set; } public double InputSurfaceArea { get; set; } } public partial class SearchResult { public string Name { get; set; } public string ViewerFile { get; set; } public string ViewerFileExtension { get; set; } public short FileType { get; set; } public string ThumbnailURL { get; set; } public ShapeSearchResult ShapeResult { get; set; } } public partial class ShapeSearchResult { public double Score { get; set; } public double Volume { get; set; } public double SurfaceArea { get; set; } } public partial class CategorySearchResult { public string Name { get; set; } public string ImageURL { get; set; } public int Count { get; set; } public string SearchFilterValue { get; set; } } public partial class Filter { public string QueryString { get; set; } public object Value { get; set; } public string HelpText { get; set; } public List FilterValues { get; set; } } public partial class ResultFilter { public string Name { get; set; } public string Value { get; set; } public string Count { get; set; } } public class ProductCategory { public int ID { get; set; } public string Name { get; set; } public string NameZH { get; set; } public ProductCategory Parent { get; set; } public string FullName { get { string str = Name.Trim(); if (Parent != null) { str = Parent.FullName + " > " + str; } return str; } } public string FullNameZH { get { if (NameZH != null) { string str = NameZH.Trim(); if (Parent != null) { str = Parent.FullNameZH + " > " + str; } return str; } else { return null; } } } } }