/// <summary>
        /// Checks a single entry agasint vulnDB Search API.
        /// </summary>
        /// <param name="consumerkey"></param>
        /// <param name="consumersecret"></param>
        /// <param name="Application"></param>
        /// <returns></returns>
        public static string vulndb_appCheck(String consumerkey, String consumersecret, String Application)
        {
            try
            {
                var requestEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/request_token");
                var authorizeEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/authorize");
                var accessEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/access_token");
                var ctx = new OAuthConsumerContext
                {
                    ConsumerKey = consumerkey,
                    ConsumerSecret = consumersecret,
                    SignatureMethod = SignatureMethod.HmacSha1
                };
                var genericSession = new OAuthSession(ctx, requestEndPoint, authorizeEndPoint, accessEndPoint);
                var targetServiceUri = new Uri("https://vulndb.cyberriskanalytics.com/api/v1/vulnerabilities/search_query?query=\"" + Application.ToString() +"\"");
                var respText = genericSession.Request().Get().ForUri(targetServiceUri).ToString();
               
                return respText;

            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                    return "Nothing Found for: " + Application.ToString();
                }
            }
        }
Example #2
0
    // основная функция конвертации
    public void convert(String FilePath, String DocmFileName)
    {
        FilePath = @"d:\1\";
        DocmFileName = "130349";
        string DocmFilePath = System.IO.Path.Combine(FilePath.ToString(), (DocmFileName.ToString() + ".docm"));
        string XmlFilePath = System.IO.Path.Combine(FilePath.ToString(), (DocmFileName.ToString() + ".xml"));
        createXML(XmlFilePath, "");
        XmlDocument document = new XmlDocument();
        document.Load(XmlFilePath);
        XmlNode element = document.CreateElement("info");
        document.DocumentElement.AppendChild(element);

        XmlNode title = document.CreateElement("title");
        title.InnerText = FilePath;
        element.AppendChild(title);

        XmlNode chapter = document.CreateElement("chapter");
        document.DocumentElement.AppendChild(chapter);

        using (WordprocessingDocument doc = WordprocessingDocument.Open(DocmFilePath, true))
        {
            var body = doc.MainDocumentPart.Document.Body;
            foreach (var text in body.Descendants<Text>())
            {
                XmlNode para = document.CreateElement("para");
                para.InnerText = text.Text;
                chapter.AppendChild(para);
            }
        }
        document.Save(XmlFilePath);
    }
Example #3
0
        public DataSet InsertGalaDinnerPaymentdate(int tourid, String paymentdate, String hotelname, String dinnertype, String cityname)
        {
            Database db = null;
            DbCommand dbCmd = null;
            DataSet dsData = null;
            try
            {

                db = DatabaseFactory.CreateDatabase(DALHelper.CRM_CONNECTION_STRING);
                dbCmd = db.GetStoredProcCommand("INSERT_PAYMENT_DATE_GALADINNER");
                db.AddInParameter(dbCmd, "@GIT_TOUR_ID", DbType.Int32, tourid);
                if (paymentdate.ToString().Equals("DD/MM/YYYY") || paymentdate.ToString().Equals(""))
                {

                    db.AddInParameter(dbCmd, "@PAYMENT_DATE", DbType.DateTime, DBNull.Value);
                }
                else
                {
                    db.AddInParameter(dbCmd, "@PAYMENT_DATE", DbType.DateTime, DateTime.ParseExact(paymentdate, "dd/MM/yyyy", null));
                }
                //db.AddInParameter(dbCmd, "@PAYMENT_DATE", DbType.String, paymentdate);
                db.AddInParameter(dbCmd, "@HOTEL_NAME", DbType.String, hotelname);
                db.AddInParameter(dbCmd, "@GALA_DINNER_TYPE_ID", DbType.String, dinnertype);
                db.AddInParameter(dbCmd, "@CITY_NAME", DbType.String, cityname);
                dsData = db.ExecuteDataSet(dbCmd);
            }
            catch (Exception ex)
            {

            }

            return dsData;
        }
Example #4
0
        public DataSet SearchPackages(String QUOTATION_NO, String FROM_DATE_S, String TO_DATE_S, String STATUS)
        {
            Database db = null;
            DbCommand dbCmd = null;
            DataSet ds = null;

            try
            {
                db = DatabaseFactory.CreateDatabase(DALHelper.CRM_CONNECTION_STRING);
                dbCmd = db.GetStoredProcCommand("SEARCH_GIT_PACKAGES");
               if(QUOTATION_NO.ToString().Equals(""))
               {
                   db.AddInParameter(dbCmd, "@QUOTATION_NO", DbType.Int32, "0");
               }
               else
                {
                db.AddInParameter(dbCmd, "@QUOTATION_NO", DbType.Int32, QUOTATION_NO);
               }

               if (FROM_DATE_S.ToString().Equals(""))
               {
                   db.AddInParameter(dbCmd, "@FROM_DATE_S", DbType.DateTime, DBNull.Value);
               }
               else
               {
                   db.AddInParameter(dbCmd, "@FROM_DATE_S", DbType.DateTime, DateTime.ParseExact(FROM_DATE_S.ToString(), "dd/MM/yyyy", null));
               }

               if (TO_DATE_S.ToString().Equals(""))
               {
                   db.AddInParameter(dbCmd, "@TO_DATE_S", DbType.DateTime, DBNull.Value);
               }
               else
               {
                   db.AddInParameter(dbCmd, "@TO_DATE_S", DbType.DateTime, DateTime.ParseExact(TO_DATE_S.ToString(), "dd/MM/yyyy", null));
               }
                
                db.AddInParameter(dbCmd, "@STATUS", DbType.String, STATUS);


                ds = db.ExecuteDataSet(dbCmd);
            }

            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, DALHelper.DAL_EXP_POLICYNAME);
                if (rethrow)
                {
                    throw ex;
                }
            }

            finally
            {
                DALHelper.Destroy(ref dbCmd);
            }
            return ds;
        }
        public String ActualizarFechaPeriodo(Decimal ID_EMPRESA, String PERIODOSPROCESO, DateTime FECHA)
        {
            Conexion conexion = new Conexion(Empresa);
            conexion.IniciarTransaccion();
            Boolean ejecutar = true;
            String sql = null;
            String informacion = null;
            String actualizado = "N";
            tools fecha = new tools();

            sql = "usp_actualizar_fecha_memorando ";

            #region validaciones
            if (ID_EMPRESA > 0)
            {
                sql += ID_EMPRESA.ToString() + ", ";
                informacion += "ID_EMPRESA= '" + ID_EMPRESA.ToString() + ", ";
            }
            else
            {
                MensajeError = "El campo ID_EMPRESA es requerido para la consulta.";
                ejecutar = false;
            }

            sql += "'" + PERIODOSPROCESO.ToString() + "', ";
            informacion += "PERIODOSPROCESO = '" + PERIODOSPROCESO.ToString() + "', ";

            sql += "'" + fecha.obtenerStringConFormatoFechaSQLServer(FECHA) + "', ";
            informacion += "FECHA = '" + FECHA.ToString() + "', ";

            sql += "'" + Usuario.ToString() + "'";
            informacion += "USU_MOD = '" + Usuario.ToString() + "'";
            #endregion

            if (ejecutar)
            {
                try
                {
                    conexion.ExecuteNonQuery(sql);
                    actualizado = "S";
                    #region auditoria
                    auditoria _auditoria = new auditoria(Empresa);
                    _auditoria.Adicionar(Usuario, tabla.NOM_PERIODO, tabla.ACCION_LIQUIDAR, sql, informacion, conexion);
                    #endregion auditoria
                    conexion.AceptarTransaccion();
                }
                catch (Exception e)
                {
                    MensajeError = e.Message;
                    conexion.DeshacerTransaccion();
                }
                finally
                {
                    conexion.Desconectar();
                }
            }
            return actualizado;
        }
Example #6
0
 public static void Error(String error)
 {
     System.Diagnostics.Debug.WriteLine(error.ToString());
     using (StreamWriter file = new StreamWriter(@"Exceptions.txt", true))
     {
         file.WriteLine(error.ToString());
         file.Close();
     }
 }
Example #7
0
 public Parser(String FilePath, String DocxFileName)
 {
     document = new XmlDocument();
        DocxFilePath = System.IO.Path.Combine(FilePath.ToString(), (DocxFileName.ToString() + ".docx"));
        XmlFilePath = System.IO.Path.Combine(FilePath.ToString(), (DocxFileName.ToString() + ".xml"));
        wordProcessingDoc = WordprocessingDocument.Open(DocxFilePath, true);
        imgPart = wordProcessingDoc.MainDocumentPart.ImageParts.ToList();
        imgPart.Reverse();
        pathString = System.IO.Path.Combine(FilePath, "img");
 }
        public static ExtensibleData Resolve(String @ref, Gx.Gedcomx document)
        {
            if ([email protected]().StartsWith("#"))
            {
                return null;
            }

            GedcomxLocalReferenceResolver visitor = new GedcomxLocalReferenceResolver(@ref.ToString().Substring(1));
            document.Accept(visitor);
            return visitor.Resource;
        }
Example #9
0
        public DataSet fetchallInvoice(String sp_name, String QID, String INVOICE, String param5, String param6, String param7,String agent_id)
        {
            Database db = null;
            DbCommand dbCmd = null;
            DataSet dsData = null;

            try
            {
                if (param5 == "0")
                {
                    param5 = "";
                }
                db = DatabaseFactory.CreateDatabase(DALHelper.CRM_CONNECTION_STRING);
                dbCmd = db.GetStoredProcCommand(sp_name);
                // db.AddInParameter(dbCmd, "@USERID", DbType.Int32, int.Parse(param1));
                db.AddInParameter(dbCmd, "@QUOTE_ID", DbType.Int32, int.Parse(QID));
                //db.AddInParameter(dbCmd, "@AGENT_NAME_S", DbType.String, AGENT);
                //db.AddInParameter(dbCmd, "@CLIENT_NAME_S", DbType.String, param3);
                //db.AddInParameter(dbCmd, "@TOUR_NAME_S", DbType.String, param4);
                db.AddInParameter(dbCmd, "@INVOICE_NO", DbType.String, INVOICE);
                if (param6.ToString().Equals(""))
                {
                    db.AddInParameter(dbCmd, "@PERIOD_STAY_FROM", DbType.DateTime, DBNull.Value);
                }
                else
                {
                    db.AddInParameter(dbCmd, "@PERIOD_STAY_FROM", DbType.DateTime, DateTime.ParseExact(param6.ToString(), "dd/MM/yyyy", null));
                }
                if (param7.ToString().Equals(""))
                {
                    db.AddInParameter(dbCmd, "@PERIOD_STAY_TO", DbType.DateTime, DBNull.Value);
                }
                else
                {
                    db.AddInParameter(dbCmd, "@PERIOD_STAY_TO", DbType.DateTime, DateTime.ParseExact(param7.ToString(), "dd/MM/yyyy", null));
                }
                if (param5.ToString().Equals(""))
                {
                    db.AddInParameter(dbCmd, "@INVOICE_DATE", DbType.DateTime, DBNull.Value);
                }
                else
                {
                    db.AddInParameter(dbCmd, "@INVOICE_DATE", DbType.DateTime, DateTime.ParseExact(param5.ToString(), "dd/MM/yyyy", null));
                }
                db.AddInParameter(dbCmd, "@AGENT_ID", DbType.Int32, int.Parse(agent_id));
                dsData = db.ExecuteDataSet(dbCmd);
            }
            catch (Exception ex)
            {

            }

            return dsData;
        }
       public DataSet fetchallDatasearch(String sp_name, String invoice_no, String voucher_status, String voucher_type, String gl_code, String from_date, String to_date, String sales_invoice, String supplier_type, String supplier_name)
       {
           Database db = null;
           DbCommand dbCmd = null;
           DataSet dsData = null;

           try
           {
               //if (param5 == "0")
               //{
               //    param5 = "";
               //}
               db = DatabaseFactory.CreateDatabase(DALHelper.CRM_CONNECTION_STRING);
               dbCmd = db.GetStoredProcCommand(sp_name);
               db.AddInParameter(dbCmd, "@INVOICE_NO", DbType.String, invoice_no);
               db.AddInParameter(dbCmd, "@VOUCHER_STATUS", DbType.String, voucher_status);

               db.AddInParameter(dbCmd, "@VOUCHER_TYPE", DbType.String, voucher_type);
               db.AddInParameter(dbCmd, "@GL_CODE", DbType.String, gl_code);
               //db.AddInParameter(dbCmd, "@TOUR_NAME_S", DbType.String, param4);
               //db.AddInParameter(dbCmd, "@STATUS", DbType.String, param5);
               if (from_date.ToString().Equals(""))
               {
                   db.AddInParameter(dbCmd, "@FROM_DATE_S", DbType.DateTime, DBNull.Value);
               }
               else
               {
                   db.AddInParameter(dbCmd, "@FROM_DATE_S", DbType.DateTime, DateTime.ParseExact(from_date.ToString(), "dd/MM/yyyy", null));
               }
               if (to_date.ToString().Equals(""))
               {
                   db.AddInParameter(dbCmd, "@TO_DATE_S", DbType.DateTime, DBNull.Value);
               }
               else
               {
                   db.AddInParameter(dbCmd, "@TO_DATE_S", DbType.DateTime, DateTime.ParseExact(to_date.ToString(), "dd/MM/yyyy", null));
               }

               db.AddInParameter(dbCmd, "@SALES_INVOICE", DbType.String, sales_invoice );
               db.AddInParameter(dbCmd, "@SUPPLIER_TYPE", DbType.String, supplier_type);
               db.AddInParameter(dbCmd, "@SUPPLIER_NAME", DbType.String, supplier_name);
               
               dsData = db.ExecuteDataSet(dbCmd);
           }
           catch (Exception ex)
           {

           }

           return dsData;
       }
Example #11
0
        public Boolean Purchase(String ProductID, int Quantity, String APIKey, string[] customercardinfo)
        {
            //copied and pasted code from project3ws and modiefied to work with this project
            //my verify method was super weird and very specific to the previous project
            //however i still use the basic functionality with the verifyinfo stored procedure
            DBConnect db = new DBConnect();
            SqlCommand command = new SqlCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "UpdateProduct";
            command.Parameters.AddWithValue("@productID", int.Parse(ProductID.ToString()));
            command.Parameters.AddWithValue("@quantity", Quantity);
            command.Parameters.AddWithValue("@API", APIKey);
            db.DoUpdateUsingCmdObj(command);
            //-------------------------update product-------------------------------------------------

            //-------------------------------update customer--------------------------------------------
            SqlCommand hank = new SqlCommand();
            hank.CommandType = CommandType.StoredProcedure;
            hank.CommandText = "UpdateCustomer";
            hank.Parameters.AddWithValue("@Email", customercardinfo[0]);
            hank.Parameters.AddWithValue("@productID", int.Parse(ProductID.ToString()));
            hank.Parameters.AddWithValue("@Quantity", Quantity);
            hank.Parameters.AddWithValue("@Name", customercardinfo[1]);
            hank.Parameters.AddWithValue("@ShippingAddress", customercardinfo[2]);
            hank.Parameters.AddWithValue("@ShippingCity", customercardinfo[3]);
            hank.Parameters.AddWithValue("@ShippingState", customercardinfo[4]);
            hank.Parameters.AddWithValue("@ShippingCountry", customercardinfo[5]);
            hank.Parameters.AddWithValue("@ShippingZipCode", customercardinfo[6]);
            hank.Parameters.AddWithValue("@BillingAddress", customercardinfo[7]);
            hank.Parameters.AddWithValue("@BillingCity", customercardinfo[8]);
            hank.Parameters.AddWithValue("@BillingState", customercardinfo[9]);
            hank.Parameters.AddWithValue("@BillingZip", customercardinfo[10]);

               // int RETVAL = 0;
               // string tempTest = command.Parameters["@RETVAL"].Value.ToString();
            //RETVAL = int.Parse(tempTest);

            //SqlCommand c = new SqlCommand();
            //c.CommandType = CommandType.StoredProcedure;
            //c.CommandText = "TPVerifyInfo";
            //c.Parameters.AddWithValue("@CreditCardNum", customercardinfo[11]);
            //c.Parameters.AddWithValue("@CVV", customercardinfo[12]);
            //db.DoUpdateUsingCmdObj(c);

            if (db.DoUpdateUsingCmdObj(hank) > 0)
            {
                return true;
            }
            return true;
        }
Example #12
0
 public Course(
     Int64 id, 
     String name, 
     String description, 
     Double units, 
     Boolean isLaboratory, 
     Boolean isServiceCourse,
     AvailabilityEnum availability)
 {
     this.id = id;
     this.name = name;
     this.description = description;
     this.units = units;
     this.isLaboratory = isLaboratory;
     this.isServiceCourse = isServiceCourse;
     this.availability = availability;
     SubItems[0].Text = name.ToString();
     SubItems.Add(description.ToString());
     SubItems.Add(units.ToString());
     SubItems.Add(isLaboratory ? "Yes" : "No");
     SubItems.Add(isServiceCourse ? "Yes" : "No");
     SubItems.Add(availability == AvailabilityEnum.EverySemester ? "Every Semester" :
                 availability == AvailabilityEnum.FirstSemesterOnly ? "1st Semester Only" :
                     "2nd Semester Only");
 }
Example #13
0
        public void StartClientServer(String ip, int port)
        {
            string ipString = ip.ToString();
            // Parse client ip address
            IPAddress ipaddress = IPAddress.Parse(ipString);  // Format exception

            // Initialize client listener
            listener = new TcpListener(ipaddress, port);

            // Set loop variable
            Boolean loop = true;
            try
            {
                // Start listening on client port
                listener.Start();

                while (loop)
                {
                    Socket newClient = listener.AcceptSocket();
                    ClientThreadHandler cth = new ClientThreadHandler(newClient);
                    cth.StartHandling();
                }
            }catch(Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
Example #14
0
        public static void Set(String uri, Style style)
        {
            System.Drawing.Image img = Image.FromStream(new System.Net.WebClient().OpenRead(uri.ToString()));

            // 将图片保存到本地目录
            img.Save(Environment.GetEnvironmentVariable("Temp") + "\\" + ImageName, System.Drawing.Imaging.ImageFormat.Bmp);

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            if (style == Style.Stretched)
            {
                key.SetValue(@"WallpaperStyle", 2.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }
            else if (style == Style.Centered)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }
            else if (style == Style.Tiled)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 1.ToString());
            }

            // 设置桌面壁纸的API
            SystemParametersInfo(SPI_SETDESKWALLPAPER
                                , 0
                                , Environment.GetEnvironmentVariable("Temp") + "\\" + ImageName
                                , SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
        }
Example #15
0
        public static IEnumerable<DirectDebitWrokFlowDetails> DetailsByDirectDebitWorkFlowRecordList(String DirectDebitID, String DueDate)
        {
            IEnumerable<DirectDebitWrokFlowDetails> List = null;
             using (var context = new SycousCon())
             {
                 try
                 {
                     var parDirectDebit = new SqlParameter
                     {
                         ParameterName = "DirectDebitID",
                         Value =  Convert.ToInt32(DirectDebitID),
                         Direction = ParameterDirection.Input
                     };
                     var parDueDate = new SqlParameter
                     {
                         ParameterName = "DueDate",
                         Value = Commmon.DateGB(DueDate.ToString()),
                         Direction = ParameterDirection.Input
                     };

                     List = context.ExecuteStoreQuery<DirectDebitWrokFlowDetails>("exec SYCOUS.GetDetailsByDirectDebit @DirectDebitID,@DueDate", parDirectDebit, parDueDate).ToList();
                 }
                 catch (Exception ex)
                 {
                     context.Dispose();
                     throw;
                 }
             }//using
             return List;
        }
Example #16
0
        public static IEnumerable<DirectDebitWrokFlow> DirectDebitWorkFlowRecordList(String ProcessingDate)
        {
            IEnumerable<DirectDebitWrokFlow> List = null;
            using (var context = new SycousCon())
            {
                try
                {
                    var parDate = new SqlParameter
                    {
                        ParameterName = "ProcessingDate",
                        Value = Commmon.DateGB(ProcessingDate.ToString()),
                        Direction = ParameterDirection.Input
                    };
             // List = context.ExecuteStoreQuery<DirectDebitWrokFlow>("exec SYCOUS.GenerateDirectDebitWorkFlow @ProcessingDate", parDate).ToList();

                    List = context.ExecuteStoreQuery<DirectDebitWrokFlow>("exec SYCOUS.GenerateDirectDebitWorkFlow @ProcessingDate", parDate).ToList();

                }
                catch (Exception ex)
                {
                    context.Dispose();
                    throw;
                }
            }//using
            return List;
        }
        public DataTable fetchCruiseDetailForSearch(String from_date, String to_date, String city, String serach_param)
        {
            Database db = null;
            DbCommand dbCmd = null;
            DataSet ds = null;

            try
            {
                db = DatabaseFactory.CreateDatabase(DALHelper.CRM_CONNECTION_STRING);
                dbCmd = db.GetStoredProcCommand("FETCH_CRUISE_DETAIL_FOR_CART_SEARCH");
                db.AddInParameter(dbCmd, "@FROM_DATE", DbType.DateTime, DateTime.ParseExact(from_date.ToString(), "dd/MM/yyyy", null));
                db.AddInParameter(dbCmd, "@TO_DATE", DbType.DateTime, DateTime.ParseExact(to_date.ToString(), "dd/MM/yyyy", null));
                db.AddInParameter(dbCmd, "@CITY", DbType.String, city);
                db.AddInParameter(dbCmd, "@SEARCH_PARAM", DbType.String, serach_param);
                ds = db.ExecuteDataSet(dbCmd);
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, DALHelper.DAL_EXP_POLICYNAME);
                if (rethrow)
                {
                    throw ex;
                }
            }
            finally
            {
                DALHelper.Destroy(ref dbCmd);
            }
            return ds.Tables[0];
        }
//        public override Object decode(Stream aux)
        public Clase03Array decode(String s)
        {
            int v1 = 0;
            int numEle1 = 0;
            string v2 = "";
            int numEle2 = 0;

            Clase03Array cOut = new Clase03Array();
            String aux = s.ToString();
            String[] parametros = aux.Split(',');

            // Se esperan dos parámetros: un int y un string
            if (parametros.Length == 4)
            {
                v1 = Convert.ToInt16(parametros[0]);
                numEle1 = Convert.ToInt16(parametros[1]);
                v2 = parametros[2];
                numEle2 = Convert.ToInt16(parametros[3]);
            }

            cOut.var1 = new int[numEle1];
            for (int i = 0; i < numEle1; i++)
            {
                cOut.var1[i] = i;
            }

            cOut.var2 = new string[numEle2];
            for (int i = 0; i < numEle2; i++)
            {
                cOut.var2[i] = Convert.ToString(i);
            }

            return cOut;
        }
Example #19
0
        private static bool Validate(String filename, XmlSchemaSet schemaSet)
        {
            Console.WriteLine("Validating XML file {0}...", filename.ToString());

            XmlSchema compiledSchema = null;

            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                compiledSchema = schema;
            }

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(compiledSchema);
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
            settings.ValidationType = ValidationType.Schema;

            success = true;

            //Create the schema validating reader.
            XmlReader vreader = XmlReader.Create(filename, settings);

            while (vreader.Read()) { }

            //Close the reader.
            vreader.Close();
            return success;
        }
Example #20
0
        public ActionResult Edit(String Id)
        {
            ViewBag.SubmitValue = "Update";
                master.Action = "SelectonID";
                TempData["id"] = Id.ToString();
                master.C_Id = Convert.ToInt32(Id);
                DataSet ds = master.coursemaster(master);

                TempData["Name"] = ds.Tables[0].Rows[0]["Name"].ToString();
                TempData["Location"] = ds.Tables[0].Rows[0]["Location"].ToString();
                TempData["Duration"] = ds.Tables[0].Rows[0]["Duration"].ToString();
                TempData["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
                TempData["Date"] = ds.Tables[0].Rows[0]["Date"].ToString();
                List<SelectListItem> items = new List<SelectListItem>();
                items.Add(new SelectListItem { Text = ds.Tables[0].Rows[0]["Tname"].ToString(), Value = ds.Tables[0].Rows[0]["Tid"].ToString() });
                ViewData["Type"] = items;
                TempData["ID"] = ds.Tables[0].Rows[0]["ID"].ToString();
                TempData["SubmitValue"] = "Update";
                if (master == null)
                {
                    return HttpNotFound();
                }
                coursedata();
                return View("~/Views/Home/Coursemaster.cshtml");
        }
        public void GetJourneylist(String StrDeviceId, FrmRegistration obj)
        {
            try
            {
                ObjFrmRegistration = obj;
                if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType != Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None)
                {
                    envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<device><deviceid>" + StrDeviceId.ToString() + "</deviceid></device>";

                    Uri RequestJourneylistlUri = new Uri(ClsCommon.WebserviceLink + "?action=check_registered_device");

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(RequestJourneylistlUri);
                    req.Credentials = ClsCommon.cred;
                    req.ContentType = "text/xml;charset=\"utf-8\"";
                    req.Accept = "text/xml";
                    req.Method = "POST";
                    req.BeginGetRequestStream(searchOnlineRequest, req);
                    RequestJourneylistlUri = null;
                }

                else
                {
                    MessageBox.Show("Internet connection not available. Please try again later!");
                }
            }
            catch
            { }
        }
        private string GetURL(String method, String walletProviderId, String walletId)
        {
            string url;
            if (this.environment == Environments.Environment.PRODUCTION)
            {
                url = PRODUCTION_URL;
            }
            else if (this.environment == Environments.Environment.MTF)
            {
                url = MTF_URL;
            }
            else
            {
                url = SANDBOX_URL;
            }

            url = url.Replace("<wallet_provider_id>", walletProviderId.ToString());
            if ((!method.Equals("POST")) && walletId != null)
            {
                url = url.Replace("<wallet_id>", walletId.ToString());
            }
            else
            {
                url = url.Replace("/<wallet_id>", "");
            }

            return url;
        }
Example #23
0
        private String GetPdfText(String year, String servantID)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www1.fgmaiss.com.br/contabil/relflh/flhrel037pdf.php?prc=MjkuMTM4LjM3Ny8wMDAxLTkz&etd=MDE=&ser=" + servantID + "&ano=" + year + "&fv1=300&fv2=000&fv3=000&fv4=000&fv5=000&fv00=500&fv01=186&fv02=008&fv03=012&fv04=071&fv05=007&fv06=073&fv07=189&fv08=406&fv09=039&fv10=041&fv11=000&fv12=000&fv13=000&fv14=000&fv15=000");
            request.Host = "www1.fgmaiss.com.br";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Cookie("8jpo2jrlp3005q3lj3qsbf5hq7PESQGRIDfindGrid", "") { Domain = request.Host });
            request.CookieContainer.Add(new Cookie("PHPSESSID", Cookie) { Domain = request.Host });
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            ServicePointManager.Expect100Continue = true;

            //salva conteúdo da resposta (pdf) http em um arquivo
            var responseStream = request.GetResponse().GetResponseStream();
            String pdfFilePath = "c:/parsal/" + servantID +  year.ToString() + ".pdf";
            var pdfOut = File.Create(pdfFilePath);
            responseStream.CopyTo(pdfOut);
            pdfOut.Close();

            //resultado
            StringBuilder pdfText = new StringBuilder();
            PdfReader pdfReader = new PdfReader(pdfFilePath);
            for (int i = 1; i <= pdfReader.NumberOfPages; i++)
                pdfText.Append(PdfTextExtractor.GetTextFromPage(pdfReader, i));

            return pdfText.ToString();
        }
Example #24
0
        // this part is going to receive client calls
        public void connect(String logging_UserName)
        {
            UserDetail User;

            if (ConnectedUsers.Count(x => x.userName == logging_UserName) == 0)
            {
                User = new UserDetail(logging_UserName.ToString(), Context.ConnectionId.ToString());
                ConnectedUsers.Add(User);
            }
            else {
                User = ConnectedUsers.Find(x => x.userName == logging_UserName);
            }

            //send to other
            //new user arrived
            Clients.Others.ReceiveNewUser(User);

            //send to caller
            //list others users
            Clients.Caller.ReceiveAllUser(ConnectedUsers);

            //send to caller
            //old messages
            Clients.Caller.ReceiveOldMessages(CurrentMessages);
        }
        static private String GenerateSignedUrl(String baseRequestTokenUrl, String method, OAuthConsumerContext context, OAuthToken token)
        {
            String normalizedUrl;
            String normalizedRequestParameters;

            var oAuth = new OAuthBase();

            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string sig = oAuth.GenerateSignature(   new Uri(baseRequestTokenUrl),
                                                    context.ConsumerKey, context.ConsumerSecret,
                                                    token == null ? string.Empty : token.TokenKey, token == null ? string.Empty : token.TokenSecret,
                                                    method.ToString(), timeStamp, nonce,
                                                    context.SignatureMethod,
                                                    out normalizedUrl, out normalizedRequestParameters);

            //
            // The signature as self has to be encoded to be ensure that no not url compatibale characters 
            // will be used. The SHA1 hash can contain a bunch of this characters
            //
            sig = HttpUtility.UrlEncode(sig);

            var sb = new StringBuilder(normalizedUrl);

            sb.AppendFormat("?");
            sb.AppendFormat(normalizedRequestParameters);
            sb.AppendFormat("&oauth_signature={0}", sig);

            return sb.ToString();
        }
Example #26
0
        public DataTable ObtenerNominasHojaTrabajo(Decimal ID_EMPRESA, String ID_EMPRESAS, String ANALISTA)
        {
            Conexion conexion = new Conexion(Empresa);
            DataSet _dataSet = new DataSet();
            DataView _dataView = new DataView();
            DataTable _dataTable = new DataTable();
            String sql = null;
            Boolean ejecutar = true;

            sql = "usp_obtener_nomina_proceso_hoja_trabajo ";

            #region validaciones
            if (ID_EMPRESA > 0)
            {
                sql += ID_EMPRESA.ToString() + " ";
            }
            else
            {
                sql += "0" + " ";
            }

            if (!(String.IsNullOrEmpty(ID_EMPRESAS)))
            {
                sql += ", '" + ID_EMPRESAS.ToString() + "'";
            }
            else
            {
                sql += ",''";
            }

            if (!(String.IsNullOrEmpty(ANALISTA)))
            {
                sql += ", '" + ANALISTA.ToString() + "'";
            }
            else
            {
                sql += ",''";
            }

            #endregion

            if (ejecutar == true)
            {
                try
                {
                    _dataSet = conexion.ExecuteReader(sql);
                    _dataView = _dataSet.Tables[0].DefaultView;
                    _dataTable = _dataView.Table;
                }
                catch (Exception e)
                {
                    MensajeError = e.Message;
                }
                finally
                {
                    conexion.Desconectar();
                }
            }
            return _dataTable;
        }
        public bool KeyPressed(String key)
        {
            Keys checkKey = (Keys)Enum.Parse(typeof(Keys), key.ToString());
            bool keyPressed = Current.IsKeyDown(checkKey) && Previous.IsKeyUp(checkKey);

            return keyPressed;
        }
Example #28
0
        public static String DateGBString(String udate)
        {
            String dtstr = String.Empty;
            DateTime dateVal;

            String returndate = String.Empty;

            try
            {
                if (!String.IsNullOrEmpty(udate))
                {
                    IFormatProvider culture = new CultureInfo("en-GB", true);
                    dateVal = DateTime.Parse(udate.ToString(), culture);

                    dtstr = dateVal.ToString("dd/MM/yyyy");
                    returndate = dtstr.Replace("/", "-");
                }

            }
            catch (Exception ex)
            {
                throw;
            }
            return returndate;
        }
    private void ShowTheFile(String EstNum, String seqNum)
    {
        // Define SQL select statement

        string SQL = "SELECT document,doc_mime_type from Project_documents WHERE EstNum = " + EstNum.ToString() + " AND seq_num = " + seqNum.ToString();
        // Create Connection object
        SqlConnection dbConn = null;
        dbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection String"].ConnectionString);
        // Create Command Object
        SqlCommand dbComm = new SqlCommand(SQL, dbConn);
        // Open Connection
        dbConn.Open();
        // Execute command and receive DataReader
        SqlDataReader dbRead = dbComm.ExecuteReader();
        // Read row
        dbRead.Read();
        // Clear Response buffer
        Response.Clear();
        // Set ContentType to the ContentType of our file
        Response.ContentType = (string)dbRead["doc_mime_type"];
        Response.BinaryWrite((byte[])dbRead["document"]);
        // Write data out of database into Output Stream
        //Response.OutputStream.Write((byte[])dbRead["ABSTRACT_DOCUMENT"], 0, (int)dbRead["CONTENT_SIZE"]);
        // Close database connection
        dbConn.Close();
        // End the page
        Response.End();
    }
Example #30
0
    public static Int32 validarUsuario(String usr, String pass)
    {
        String query = "SELECT idUsuario FROM usuario " +
            "WHERE user='******'" +
            "AND   password='******'";
        try
        {

            using (OdbcConnection con = new OdbcConnection(Constantes.CONNECTION_STRING))
            {
                using (OdbcCommand cmd = new OdbcCommand(query, con))
                {
                    con.Open();
                    cmd.CommandType = CommandType.Text;
                    Int32 idUser = Convert.ToInt32(cmd.ExecuteScalar());
                    cmd.Connection.Close();

                    return idUser;
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
Example #31
0
 // this method prevents inlining the final version constant in compiled
 // classes,
 // see: http://www.javaworld.com/community/node/3400
 private static System.String Ident(System.String s)
 {
     return(s.ToString());
 }
Example #32
0
File: SaleOp.cs Project: sky-tc/U8
        /// <summary>
        /// 激发API操作
        /// </summary>
        /// <param name="broker"></param>
        /// <returns></returns>
        public override Model.DealResult BrokerInvoker(UFIDA.U8.U8APIFramework.U8ApiBroker broker)
        {
            Model.DealResult        dr        = new Model.DealResult();
            MSXML2.IXMLDOMDocument2 domResult = new MSXML2.DOMDocument();

            MSXML2.IXMLDOMNodeList lstx;
            string sResult = "";

            if (!broker.Invoke())
            {
                //错误处理
                Exception apiEx = broker.GetException();
                if (apiEx != null)
                {
                    if (apiEx is MomSysException)
                    {
                        MomSysException sysEx = apiEx as MomSysException;
                        dr.ResultNum = -1;
                        dr.ResultMsg = "系统异常:" + sysEx.Message;
                    }
                    else if (apiEx is MomBizException)
                    {
                        MomBizException bizEx = apiEx as MomBizException;
                        dr.ResultNum = -1;
                        dr.ResultMsg = "API异常:" + bizEx.Message;
                    }

                    String exReason = broker.GetExceptionString();
                    if (exReason.Length != 0)
                    {
                        dr.ResultNum = -1;
                        dr.ResultMsg = " 异常原因:" + exReason;
                    }
                }

                broker.Release();

                return(dr);
            }
            System.String result    = broker.GetReturnValue() as System.String;
            string        vNewIDRet = broker.GetResult("vNewID") as string;

            broker.Release();


            if (result != null)
            {
                dr.ResultNum = -1;
                dr.ResultMsg = result;
                sResult      = result.ToString();

                //增加可用量不足的提示,通过读取返回的DOM信息解析可用量不足的信息
                if (sResult.IndexOf("<rs:data") > 0)
                {
                    string sInvCode = "";
                    string sInvName = "";
                    string sWhCode  = "";
                    string sWhName  = "";
                    string sError   = "";
                    sResult = sResult.Substring(sResult.IndexOf("<rs:data"));
                    if (domResult.loadXML(sResult) == true)
                    {
                        lstx = domResult.selectNodes("//z:row");
                        foreach (MSXML2.IXMLDOMNode xmle in lstx)
                        {
                            sInvCode = xmle.attributes.getNamedItem("cinvcode").nodeValue.ToString();
                            sInvName = xmle.attributes.getNamedItem("cinvname").nodeValue.ToString();
                            sWhCode  = xmle.attributes.getNamedItem("cwhcode").nodeValue.ToString();
                            sWhName  = xmle.attributes.getNamedItem("cwhname").nodeValue.ToString();

                            sError = sError + "存货编码[" + sInvCode + "] 存货名称[" + sInvName + "] 仓库[" + sWhName + "]\r\n";
                        }
                        if (sError != "")
                        {
                            sError       = sError + "可用量不足";
                            result       = sError;
                            dr.ResultMsg = result;
                        }
                    }
                }

                throw new Exception("API错误:" + result);
            }
            dr.VouchIdRet = vNewIDRet;
            return(dr);
        }
Example #33
0
        public static string InsertProduct(DataTable dthead, DataTable dtbody)
        {
            U8EnvContext envContext = new U8EnvContext();

            envContext.U8Login = canshu.u8Login;
            //envContext.U8Login = u8Login;
            //第三步:设置API地址标识(Url)
            //当前API:添加新单据的地址标识为:U8API/MaterialOut/Add
            U8ApiAddress myApiAddress = new U8ApiAddress("U8API/ARClose/SaveVouch");

            //第四步:构造APIBroker
            U8ApiBroker broker = new U8ApiBroker(myApiAddress, envContext);

            //第五步:API参数赋值

            ////给普通参数sVouchType赋值。此参数的数据类型为System.String,此参数按值传递,表示单据类型:11
            //broker.AssignNormalValue("sVouchType", "11");
            ////该参数VouchId为INOUT型普通参数。此参数的数据类型为System.String,此参数按值传递。在API调用返回时,可以通过GetResult("VouchId")获取其值
            //string vouid = "";
            //broker.AssignNormalValue("VouchId", vouid);

            ////该参数domMsg为OUT型参数,由于其数据类型为MSXML2.IXMLDOMDocument2,非一般值类型,因此必须传入一个参数变量。在API调用返回时,可以直接使用该参数


            MSXML2.IXMLDOMDocument2 domMsg = new MSXML2.DOMDocumentClass();
            broker.AssignNormalValue("domMsg", domMsg);

            ////给普通参数bCheck赋值。此参数的数据类型为System.Boolean,此参数按值传递,表示是否控制可用量。
            //broker.AssignNormalValue("bCheck", true);

            ////给普通参数bBeforCheckStock赋值。此参数的数据类型为System.Boolean,此参数按值传递,表示检查可用量
            //broker.AssignNormalValue("bBeforCheckStock", true);


            ////给普通参数bIsRedVouch赋值。此参数的数据类型为System.Boolean,此参数按值传递,表示是否红字单据
            //broker.AssignNormalValue("bIsRedVouch", false);

            ////给普通参数sAddedState赋值。此参数的数据类型为System.String,此参数按值传递,表示传空字符串
            //string sadd = "";
            //broker.AssignNormalValue("sAddedState", sadd);

            ////给普通参数bReMote赋值。此参数的数据类型为System.Boolean,此参数按值传递,表示是否远程:转入false
            //broker.AssignNormalValue("bReMote", false);

            //打开adodb连接
            Connection oCon = new ConnectionClass();

            oCon.Open(envContext.U8Login.UfDbName);
            MSXML2.IXMLDOMDocument2 domhead = new DOMDocument();
            MSXML2.IXMLDOMDocument2 dombody = new DOMDocument();
            //表头赋值


            //表头DOM赋值
            string    sqlt = "select cast(null as nvarchar(2)) as editprop,* from AR_CloseR where 1=2 ";
            Recordset rs   = new Recordset();

            rs.Open(sqlt, oCon, CursorTypeEnum.adOpenForwardOnly, LockTypeEnum.adLockReadOnly);
            rs.Save(domhead, PersistFormatEnum.adPersistXML);
            //插入表头信息
            IXMLDOMElement eleHead = (IXMLDOMElement)domhead.selectSingleNode("//rs:data");
            IXMLDOMElement ele     = (IXMLDOMElement)domhead.createElement("z:row");

            eleHead.appendChild(ele);

            try
            {
                ele.setAttribute("editprop", "A");//A代表增加,M代表修改

                ele.setAttribute("dVouchDate", DateTime.Now.ToShortDateString());
                ele.setAttribute("cdwcode", "0999");
                //ele.setAttribute("id", rdid);
                ele.setAttribute("ccode", "100");
                ele.setAttribute("VT_ID", "65");
                ele.setAttribute("ddate", DateTime.Now.ToShortDateString());    //出库日期


                ele.setAttribute("dnmaketime", DateTime.Now.ToString()); //制单日期
                ele.setAttribute("cmemo", "下料生成");                       //备注
                ele.setAttribute("cmaker", canshu.u8Login.cUserName);    //制单人


                broker.AssignNormalValue("DomHead", domhead);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误发生", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return("0");
            }



            //表体赋值
            string sqlw = "select cast(null as nvarchar(2)) as editprop,* from recordoutsq where 1=2 ";

            //Recordset rs = new Recordset();
            rs.Close();
            rs.Open(sqlw, oCon, CursorTypeEnum.adOpenForwardOnly, LockTypeEnum.adLockReadOnly);
            rs.Save(dombody, PersistFormatEnum.adPersistXML);
            //插入表体尾信息
            //dombody.rowcount =
            IXMLDOMElement eleBody = (IXMLDOMElement)dombody.selectSingleNode("//rs:data");

            for (int i = 0; i < dtbody.Rows.Count; i++)
            {
                ele = (IXMLDOMElement)dombody.createElement("z:row");
                eleBody.appendChild(ele);

                // 表尾赋值

                //string cinvcode = "01019002063";
                //int autoid = 1000;
                //decimal sl = 4m;
                try
                {
                    ele.setAttribute("editprop", "A");
                    //ele.setAttribute("autoid", autoid);
                    ele.setAttribute("cinvcode", DbHelper.GetDbString(dtbody.Rows[i]["存货编码"]));
                    if (string.IsNullOrEmpty(DbHelper.GetDbString(dtbody.Rows[i]["lotno"])) != true)
                    {
                        ele.setAttribute("cBatch", DbHelper.GetDbString(dtbody.Rows[i]["lotno"]));
                    }

                    ele.setAttribute("iquantity", DbHelper.GetDbString(dtbody.Rows[i]["本次下料"]));
                    //MessageBox.Show(dtbody.Rows[i]["本次下料"].ToString());
                    ele.setAttribute("iMPoIds", DbHelper.GetDbInt(dtbody.Rows[i]["allocateid"]));
                    ele.setAttribute("cmocode", DbHelper.GetDbString(dthead.Rows[0]["染料单号"]));
                    ele.setAttribute("inquantity", DbHelper.GetDbdecimal(dtbody.Rows[i]["未下数量"])); //未下应下数量
                    //生产订单信息
                    ele.setAttribute("invcode", DbHelper.GetDbString(dthead.Rows[0]["色号"]));
                    ele.setAttribute("imoseq", DbHelper.GetDbString(dthead.Rows[0]["sortseq"]));
                    ele.setAttribute("iopseq", DbHelper.GetDbString(dtbody.Rows[i]["opseq"]));
                    ele.setAttribute("copdesc", DbHelper.GetDbString(dtbody.Rows[i]["工序"]));
                    ele.setAttribute("iExpiratDateCalcu", 0);
                    ele.setAttribute("irowno", i + 1);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误发生", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return("0");
                }
            }

            broker.AssignNormalValue("DomBody", dombody);

            //测试结果
            //domhead.save(@"d:\2xml");
            //dombody.save(@"d:\3.xm.l");

            //第六步:调用API
            if (!broker.Invoke())
            {
                //错误处理
                Exception apiEx = broker.GetException();
                if (apiEx != null)
                {
                    if (apiEx is MomSysException)
                    {
                        MomSysException sysEx = apiEx as MomSysException;
                        MessageBox.Show("系统异常:" + sysEx.Message);
                        //todo:异常处理
                    }
                    else if (apiEx is MomBizException)
                    {
                        MomBizException bizEx = apiEx as MomBizException;
                        MessageBox.Show("API异常:" + bizEx.Message);
                        //todo:异常处理
                    }
                    //异常原因
                    String exReason = broker.GetExceptionString();
                    if (exReason.Length != 0)
                    {
                        MessageBox.Show("异常原因:" + exReason);
                    }
                }
                //结束本次调用,释放API资源
                broker.Release();
                return("0");
            }

            //第七步:获取返回结果

            //获取返回值
            //获取普通返回值。此返回值数据类型为System.Boolean,此参数按值传递,表示返回值:true:成功,false:失败
            System.Boolean result = Convert.ToBoolean(broker.GetReturnValue());

            if (result == false)
            {
                //获取普通OUT参数errMsg。此返回值数据类型为System.String,在使用该参数之前,请判断是否为空
                System.String errMsgRet = broker.GetResult("errMsg") as System.String;
                if (errMsgRet != null)
                {
                    MessageBox.Show(errMsgRet.ToString(), "错误提示1!");
                }
                return("2");
                //MessageBox.Show(result.ToString(), "导入成功提示");
            }
            ////获取out/inout参数值

            ////获取普通OUT参数errMsg。此返回值数据类型为System.String,在使用该参数之前,请判断是否为空
            //System.String errMsgRet = broker.GetResult("errMsg") as System.String;
            //if (errMsgRet != null)
            //    MessageBox.Show(errMsgRet.ToString(), "错误提示1!");

            ////获取普通INOUT参数VouchId。此返回值数据类型为System.String,在使用该参数之前,请判断是否为空
            System.String VouchIdRet = broker.GetResult("VouchId") as System.String;

            ////获取普通OUT参数domMsg。此返回值数据类型为MSXML2.IXMLDOMDocument2,在使用该参数之前,请判断是否为空
            //MSXML2.IXMLDOMDocument2 domMsgRet = (broker.GetResult("domMsg")) as MSXML2.IXMLDOMDocument2;
            //if (domMsgRet != null)
            //    MessageBox.Show(domMsgRet.ToString(), "错误提示2!");
            //结束本次调用,释放API资源
            broker.Release();
            return(VouchIdRet);
        }
        public void ContentDirectory_Browse(System.String ObjectID, DvContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, out System.String Result, out System.UInt32 NumberReturned, out System.UInt32 TotalMatches, out System.UInt32 UpdateID)
        {
            Console.WriteLine("DEVICE ContentDirectory_Browse(" + ObjectID.ToString() + BrowseFlag.ToString() + Filter.ToString() + StartingIndex.ToString() + RequestedCount.ToString() + SortCriteria.ToString() + ")");

            Result         = "Sample String";
            NumberReturned = 0;
            TotalMatches   = 0;
            UpdateID       = 0;

            if (BrowseFlag == DvContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN)
            {
                switch (ObjectID)
                {
                case "0":     // root
                    NumberReturned = S2count;
                    TotalMatches   = S2count;
                    Result         = S2;
                    break;
                }
            }
        }
 public void ContentDirectory_Search(System.String ContainerID, System.String SearchCriteria, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, out System.String Result, out System.UInt32 NumberReturned, out System.UInt32 TotalMatches, out System.UInt32 UpdateID)
 {
     Result         = "Sample String";
     NumberReturned = 0;
     TotalMatches   = 0;
     UpdateID       = 0;
     Console.WriteLine("ContentDirectory_Search(" + ContainerID.ToString() + SearchCriteria.ToString() + Filter.ToString() + StartingIndex.ToString() + RequestedCount.ToString() + SortCriteria.ToString() + ")");
 }
        /// <summary> Returns whether <code>a</code> is less relevant than <code>b</code>.</summary>
        /// <param name="a">ScoreDoc
        /// </param>
        /// <param name="b">ScoreDoc
        /// </param>
        /// <returns> <code>true</code> if document <code>a</code> should be sorted after document <code>b</code>.
        /// </returns>
        public override bool LessThan(System.Object a, System.Object b)
        {
            FieldDoc docA = (FieldDoc)a;
            FieldDoc docB = (FieldDoc)b;
            int      n    = fields.Length;
            int      c    = 0;

            for (int i = 0; i < n && c == 0; ++i)
            {
                int type = fields[i].GetType();
                switch (type)
                {
                case SortField.SCORE:
                    float r1 = (float)((System.Single)docA.fields[i]);
                    float r2 = (float)((System.Single)docB.fields[i]);
                    if (r1 > r2)
                    {
                        c = -1;
                    }
                    if (r1 < r2)
                    {
                        c = 1;
                    }
                    break;

                case SortField.DOC:
                case SortField.INT:
                    int i1 = ((System.Int32)docA.fields[i]);
                    int i2 = ((System.Int32)docB.fields[i]);
                    if (i1 < i2)
                    {
                        c = -1;
                    }
                    if (i1 > i2)
                    {
                        c = 1;
                    }
                    break;

                case SortField.STRING:
                    System.String s1 = (System.String)docA.fields[i];
                    System.String s2 = (System.String)docB.fields[i];
                    // null values need to be sorted first, because of how FieldCache.getStringIndex()
                    // works - in that routine, any documents without a value in the given field are
                    // put first.  If both are null, the next SortField is used
                    if (s1 == null)
                    {
                        c = (s2 == null)?0:-1;
                    }
                    else if (s2 == null)
                    {
                        c = 1;
                    }
                    //
                    else if (fields[i].GetLocale() == null)
                    {
                        c = String.CompareOrdinal(s1, s2);
                    }
                    else
                    {
                        //UPGRADE_TODO: The equivalent in .NET for method 'java.text.Collator.compare' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                        c = collators[i].Compare(s1.ToString(), s2.ToString());
                    }
                    break;

                case SortField.FLOAT:
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    float f1 = (float)((System.Single)docA.fields[i]);
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    float f2 = (float)((System.Single)docB.fields[i]);
                    if (f1 < f2)
                    {
                        c = -1;
                    }
                    if (f1 > f2)
                    {
                        c = 1;
                    }
                    break;

                case SortField.CUSTOM:
                    c = docA.fields[i].CompareTo(docB.fields[i]);
                    break;

                case SortField.AUTO:
                    // we cannot handle this - even if we determine the type of object (Float or
                    // Integer), we don't necessarily know how to compare them (both SCORE and
                    // FLOAT contain floats, but are sorted opposite of each other). Before
                    // we get here, each AUTO should have been replaced with its actual value.
                    throw new System.SystemException("FieldDocSortedHitQueue cannot use an AUTO SortField");

                default:
                    throw new System.SystemException("invalid SortField type: " + type);
                }
                if (fields[i].GetReverse())
                {
                    c = -c;
                }
            }

            // avoid random sort order that could lead to duplicates (bug #31241):
            if (c == 0)
            {
                return(docA.doc > docB.doc);
            }

            return(c > 0);
        }
Example #37
0
        /// <summary> Returns whether <code>a</code> is less relevant than <code>b</code>.</summary>
        /// <param name="a">ScoreDoc
        /// </param>
        /// <param name="b">ScoreDoc
        /// </param>
        /// <returns> <code>true</code> if document <code>a</code> should be sorted after document <code>b</code>.
        /// </returns>
        public override bool LessThan(System.Object a, System.Object b)
        {
            FieldDoc docA = (FieldDoc)a;
            FieldDoc docB = (FieldDoc)b;
            int      n    = fields.Length;
            int      c    = 0;

            for (int i = 0; i < n && c == 0; ++i)
            {
                int type = fields[i].GetType();
                if (fields[i].GetReverse())
                {
                    switch (type)
                    {
                    case SortField.SCORE:
                        float r1 = (float)((System.Single)docA.fields[i]);
                        float r2 = (float)((System.Single)docB.fields[i]);
                        if (r1 < r2)
                        {
                            c = -1;
                        }
                        if (r1 > r2)
                        {
                            c = 1;
                        }
                        break;

                    case SortField.DOC:
                    case SortField.INT:
                        int i1 = ((System.Int32)docA.fields[i]);
                        int i2 = ((System.Int32)docB.fields[i]);
                        if (i1 > i2)
                        {
                            c = -1;
                        }
                        if (i1 < i2)
                        {
                            c = 1;
                        }
                        break;

                    case SortField.STRING:
                        System.String s1 = (System.String)docA.fields[i];
                        System.String s2 = (System.String)docB.fields[i];
                        if (s2 == null)
                        {
                            c = -1;
                        }
                        // could be null if there are
                        else if (s1 == null)
                        {
                            c = 1;
                        }
                        // no terms in the given Field
                        else if (fields[i].GetLocale() == null)
                        {
                            c = String.CompareOrdinal(s2, s1);
                        }
                        else
                        {
                            c = collators[i].Compare(s2.ToString(), s1.ToString());
                        }
                        break;

                    case SortField.FLOAT:
                        float f1 = (float)((System.Single)docA.fields[i]);
                        float f2 = (float)((System.Single)docB.fields[i]);
                        if (f1 > f2)
                        {
                            c = -1;
                        }
                        if (f1 < f2)
                        {
                            c = 1;
                        }
                        break;

                    case SortField.CUSTOM:
                        c = docB.fields[i].CompareTo(docA.fields[i]);
                        break;

                    case SortField.AUTO:
                        // we cannot handle this - even if we determine the type of object (Float or
                        // Integer), we don't necessarily know how to compare them (both SCORE and
                        // FLOAT both contain floats, but are sorted opposite of each other). Before
                        // we get here, each AUTO should have been replaced with its actual value.
                        throw new System.SystemException("FieldDocSortedHitQueue cannot use an AUTO SortField");

                    default:
                        throw new System.SystemException("invalid SortField type: " + type);
                    }
                }
                else
                {
                    switch (type)
                    {
                    case SortField.SCORE:
                        float r1 = (float)((System.Single)docA.fields[i]);
                        float r2 = (float)((System.Single)docB.fields[i]);
                        if (r1 > r2)
                        {
                            c = -1;
                        }
                        if (r1 < r2)
                        {
                            c = 1;
                        }
                        break;

                    case SortField.DOC:
                    case SortField.INT:
                        int i1 = ((System.Int32)docA.fields[i]);
                        int i2 = ((System.Int32)docB.fields[i]);
                        if (i1 < i2)
                        {
                            c = -1;
                        }
                        if (i1 > i2)
                        {
                            c = 1;
                        }
                        break;

                    case SortField.STRING:
                        System.String s1 = (System.String)docA.fields[i];
                        System.String s2 = (System.String)docB.fields[i];
                        // null values need to be sorted first, because of how FieldCache.getStringIndex()
                        // works - in that routine, any documents without a value in the given Field are
                        // put first.
                        if (s1 == null)
                        {
                            c = -1;
                        }
                        // could be null if there are
                        else if (s2 == null)
                        {
                            c = 1;
                        }
                        // no terms in the given Field
                        else if (fields[i].GetLocale() == null)
                        {
                            c = String.CompareOrdinal(s1, s2);
                        }
                        else
                        {
                            c = collators[i].Compare(s1.ToString(), s2.ToString());
                        }
                        break;

                    case SortField.FLOAT:
                        float f1 = (float)((System.Single)docA.fields[i]);
                        float f2 = (float)((System.Single)docB.fields[i]);
                        if (f1 < f2)
                        {
                            c = -1;
                        }
                        if (f1 > f2)
                        {
                            c = 1;
                        }
                        break;

                    case SortField.CUSTOM:
                        c = docA.fields[i].CompareTo(docB.fields[i]);
                        break;

                    case SortField.AUTO:
                        // we cannot handle this - even if we determine the type of object (Float or
                        // Integer), we don't necessarily know how to compare them (both SCORE and
                        // FLOAT both contain floats, but are sorted opposite of each other). Before
                        // we get here, each AUTO should have been replaced with its actual value.
                        throw new System.SystemException("FieldDocSortedHitQueue cannot use an AUTO SortField");

                    default:
                        throw new System.SystemException("invalid SortField type: " + type);
                    }
                }
            }
            return(c > 0);
        }
        public /*protected internal*/ override bool TermCompare(Term term)
        {
            if (collator == null)
            {
                // Use Unicode code point ordering
                bool checkLower = false;
                if (!includeLower)
                {
                    // make adjustments to set to exclusive
                    checkLower = true;
                }
                if (term != null && (System.Object)term.Field() == (System.Object)field)
                {
                    // interned comparison
                    if (!checkLower || null == lowerTermText || String.CompareOrdinal(term.Text(), lowerTermText) > 0)
                    {
                        checkLower = false;
                        if (upperTermText != null)
                        {
                            int compare = String.CompareOrdinal(upperTermText, term.Text());

                            /*
                             * if beyond the upper term, or is exclusive and this is equal to
                             * the upper term, break out
                             */
                            if ((compare < 0) || (!includeUpper && compare == 0))
                            {
                                endEnum = true;
                                return(false);
                            }
                        }
                        return(true);
                    }
                }
                else
                {
                    // break
                    endEnum = true;
                    return(false);
                }
                return(false);
            }
            else
            {
                if (term != null && (System.Object)term.Field() == (System.Object)field)
                {
                    // interned comparison
                    if ((lowerTermText == null || (includeLower?collator.Compare(term.Text().ToString(), lowerTermText.ToString()) >= 0:collator.Compare(term.Text().ToString(), lowerTermText.ToString()) > 0)) && (upperTermText == null || (includeUpper?collator.Compare(term.Text().ToString(), upperTermText.ToString()) <= 0:collator.Compare(term.Text().ToString(), upperTermText.ToString()) < 0)))
                    {
                        return(true);
                    }
                    return(false);
                }
                endEnum = true;
                return(false);
            }
        }
Example #39
0
 /*
  * Get the string representation of the PID. Erlang PIDs are printed
  * as #Pid&lt;node.id.serial&gt;
  *
  * @return the string representation of the PID.
  **/
 public override System.String ToString()
 {
     return("#Pid<" + _node.ToString() + "." + _id + "." + _serial + ">");
 }
Example #40
0
        public static void SalvarUsuario(System.String Usuario, System.String Senha, bool Remover = false)
        {
            string lCaminho     = gCaminho;
            string lNomeArquivo = "";

            /*
             * if (ContextoGlobal.Usuario.TipoAcesso == TipoAcesso.Assessor)
             *  lNomeArquivo = ContextoGlobal.Usuario.CodAssessor.ToString();
             * else if (ContextoGlobal.Usuario.TipoAcesso == TipoAcesso.Cliente)
             *  lNomeArquivo = ContextoGlobal.Usuario.CodBovespa;
             * else
             *  lNomeArquivo = ContextoGlobal.Usuario.NomeUsuario;
             */

            if (!Directory.Exists(gCaminho))
            {
                Directory.CreateDirectory(gCaminho);
            }

            lCaminho = System.IO.Path.Combine(lCaminho, string.Concat(lNomeArquivo, "dados", ".dat"));

            System.IO.FileStream wFile;
            wFile = new System.IO.FileStream(lCaminho, System.IO.FileMode.Create);

            try
            {
                byte[] byteData = null;

                #region Usuarios Autenticados

                byteData = Encoding.ASCII.GetBytes(String.Format("\tUSUARIO_PADRAO="));
                wFile.Write(byteData, 0, byteData.Length);
                System.Text.StringBuilder _usuario = new StringBuilder();
                if (!Remover)
                {
                    _usuario.AppendFormat("{0}:{1},", Usuario.ToString(), Senha.ToString());
                }

                _usuario.Append("\r\n");
                byteData = Encoding.ASCII.GetBytes(_usuario.ToString());
                wFile.Write(byteData, 0, byteData.Length);

                #endregion

                #region Usuarios Autenticados

                byteData = Encoding.ASCII.GetBytes(String.Format("\tUSUARIOS="));
                wFile.Write(byteData, 0, byteData.Length);
                System.Text.StringBuilder _usuarios = new StringBuilder();

                if (Aplicacao.Usuarios.ContainsKey(Usuario.ToString()))
                {
                    if (Remover)
                    {
                        Aplicacao.Usuarios.Remove(Usuario.ToString());
                    }
                    else
                    {
                        Aplicacao.Usuarios[Usuario.ToString()] = Senha.ToString();
                    }
                }
                else
                {
                    Aplicacao.Usuarios.Add(Usuario.ToString(), Senha.ToString());
                }

                foreach (var pair in Aplicacao.Usuarios)
                {
                    if (Remover)
                    {
                        if (pair.Key.Equals(Usuario))
                        {
                            continue;
                        }
                    }

                    _usuarios.AppendFormat("{0}:{1},", pair.Key.ToString(), pair.Value.ToString());
                }

                _usuarios.Append("\r\n");
                byteData = Encoding.ASCII.GetBytes(_usuarios.ToString());
                wFile.Write(byteData, 0, byteData.Length);

                #endregion
            }
            catch (Exception ex)
            {
                Aplicacao.ReportarErro("SalvarUsuario()", ex);
                throw ex;
            }
            finally
            {
                wFile.Close();
            }
        }
Example #41
0
        private static Regex compilePattern(System.String pattern, System.String escape)
        {
            // In JMS the wildcard characters are '_' (match any single character) and
            // '%' (match zero or more characters). In regular expressions the equivalent
            // wildcard characters are '.' and '*'.
            // We have to convert JMS wildcard characters in the pattern to regexp wildcard
            // characters taking care of the escape character.
            System.String             regExp = null;
            System.Text.StringBuilder buf    = new System.Text.StringBuilder();
            if ((System.Object)escape == null)
            {
                // No escape character - simply replace JMS wildcards with
                // regular expression wildcards
                for (SupportClass.Tokenizer strTok = new SupportClass.Tokenizer(pattern.Replace('_', '.'), "%"); strTok.HasMoreTokens();)
                {
                    buf.Append(strTok.NextToken());
                }
                regExp = buf.ToString();
            }
            else
            {
                char esc = escape[0];
                for (int i = 0; i < pattern.Length; ++i)
                {
                    char nextChar = pattern[i];

                    if (nextChar != esc)
                    {
                        // Not an escape character - simply replace JMS wildcard characters with
                        // regular expression wildcard characters

                        if (nextChar == '_')
                        {
                            buf.Append('.');
                        }
                        else if (nextChar == '%')
                        {
                            buf.Append(".*");
                        }
                        else
                        {
                            buf.Append(nextChar);
                        }
                    }
                    else
                    {
                        // Escape character - replace user-defined escape character with
                        // regular expression escape character. Copy the character after
                        // the escape character as is since it is being escaped

                        buf.Append('\\');
                        ++i;
                        if (i < pattern.Length)
                        {
                            buf.Append(pattern[i]);
                        }
                    }
                }
                regExp = buf.ToString();
            }
            return(new Regex(regExp.ToString()));
        }
 public void X_MS_MediaReceiverRegistrar_IsValidated(System.String DeviceID, out System.Int32 Result)
 {
     Result = 0;
     Console.WriteLine("X_MS_MediaReceiverRegistrar_IsValidated(" + DeviceID.ToString() + ")");
 }
        /// <summary> Returns whether <code>a</code> is less relevant than <code>b</code>.</summary>
        /// <param name="a">ScoreDoc
        /// </param>
        /// <param name="b">ScoreDoc
        /// </param>
        /// <returns> <code>true</code> if document <code>a</code> should be sorted after document <code>b</code>.
        /// </returns>
        public override bool LessThan(System.Object a, System.Object b)
        {
            FieldDoc docA = (FieldDoc)a;
            FieldDoc docB = (FieldDoc)b;
            int      n    = fields.Length;
            int      c    = 0;

            for (int i = 0; i < n && c == 0; ++i)
            {
                int type = fields[i].GetType();
                switch (type)
                {
                case SortField.SCORE:  {
                    float r1 = (float)((System.Single)docA.fields[i]);
                    float r2 = (float)((System.Single)docB.fields[i]);
                    if (r1 > r2)
                    {
                        c = -1;
                    }
                    if (r1 < r2)
                    {
                        c = 1;
                    }
                    break;
                }

                case SortField.DOC:
                case SortField.INT:  {
                    int i1 = ((System.Int32)docA.fields[i]);
                    int i2 = ((System.Int32)docB.fields[i]);
                    if (i1 < i2)
                    {
                        c = -1;
                    }
                    if (i1 > i2)
                    {
                        c = 1;
                    }
                    break;
                }

                case SortField.LONG:  {
                    long l1 = (long)((System.Int64)docA.fields[i]);
                    long l2 = (long)((System.Int64)docB.fields[i]);
                    if (l1 < l2)
                    {
                        c = -1;
                    }
                    if (l1 > l2)
                    {
                        c = 1;
                    }
                    break;
                }

                case SortField.STRING:  {
                    System.String s1 = (System.String)docA.fields[i];
                    System.String s2 = (System.String)docB.fields[i];
                    // null values need to be sorted first, because of how FieldCache.getStringIndex()
                    // works - in that routine, any documents without a value in the given field are
                    // put first.  If both are null, the next SortField is used
                    if (s1 == null)
                    {
                        c = (s2 == null)?0:-1;
                    }
                    else if (s2 == null)
                    {
                        c = 1;
                    }
                    //
                    else if (fields[i].GetLocale() == null)
                    {
                        c = String.CompareOrdinal(s1, s2);
                    }
                    else
                    {
                        c = collators[i].Compare(s1.ToString(), s2.ToString());
                    }
                    break;
                }

                case SortField.FLOAT:  {
                    float f1 = (float)((System.Single)docA.fields[i]);
                    float f2 = (float)((System.Single)docB.fields[i]);
                    if (f1 < f2)
                    {
                        c = -1;
                    }
                    if (f1 > f2)
                    {
                        c = 1;
                    }
                    break;
                }

                case SortField.DOUBLE:  {
                    double d1 = ((System.Double)docA.fields[i]);
                    double d2 = ((System.Double)docB.fields[i]);
                    if (d1 < d2)
                    {
                        c = -1;
                    }
                    if (d1 > d2)
                    {
                        c = 1;
                    }
                    break;
                }

                case SortField.BYTE:  {
                    int i1 = (sbyte)((System.SByte)docA.fields[i]);
                    int i2 = (sbyte)((System.SByte)docB.fields[i]);
                    if (i1 < i2)
                    {
                        c = -1;
                    }
                    if (i1 > i2)
                    {
                        c = 1;
                    }
                    break;
                }

                case SortField.SHORT:  {
                    int i1 = (short)((System.Int16)docA.fields[i]);
                    int i2 = (short)((System.Int16)docB.fields[i]);
                    if (i1 < i2)
                    {
                        c = -1;
                    }
                    if (i1 > i2)
                    {
                        c = 1;
                    }
                    break;
                }

                case SortField.CUSTOM:  {
                    c = docA.fields[i].CompareTo(docB.fields[i]);
                    break;
                }

                case SortField.AUTO:  {
                    // we cannot handle this - even if we determine the type of object (Float or
                    // Integer), we don't necessarily know how to compare them (both SCORE and
                    // FLOAT contain floats, but are sorted opposite of each other). Before
                    // we get here, each AUTO should have been replaced with its actual value.
                    throw new System.SystemException("FieldDocSortedHitQueue cannot use an AUTO SortField");
                }

                default:  {
                    throw new System.SystemException("invalid SortField type: " + type);
                }
                }
                if (fields[i].GetReverse())
                {
                    c = -c;
                }
            }

            // avoid random sort order that could lead to duplicates (bug #31241):
            if (c == 0)
            {
                return(docA.doc > docB.doc);
            }

            return(c > 0);
        }
Example #44
0
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            if (requestCode == PHOTO_REQUEST && resultCode == Result.Ok)
            {
                LaunchMediaScanIntent();
                try
                {
                    Bitmap bitmap = DecodeBitmapUri(ApplicationContext, imageUri);
                    if (detector.IsOperational && bitmap != null)
                    {
                        Frame         frame      = new Frame.Builder().SetBitmap(bitmap).Build();
                        SparseArray   textBlocks = detector.Detect(frame);
                        System.String blocks     = "";
                        System.String lines      = "";
                        System.String words      = "";
                        var           regexMoney = new Regex(@"\$ ?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$*");
                        for (int index = 0; index < textBlocks.Size(); index++)
                        {
                            //extract scanned text blocks here
                            TextBlock tBlock = (TextBlock)textBlocks.ValueAt(index);
                            blocks = blocks + tBlock.Value + " " + "\n";
                            var   text  = Regex.Replace(blocks.ToString(), "[A-Za-z ]", " ");
                            Match match = regexMoney.Match(text);
                            if (match.Success)
                            {
                                scanResults.Text = match.Value;
                                break;
                            }
                            else
                            {
                                scanResults.Text = "No Price.";
                            }

                            //    foreach (IText line in tBlock.Components)
                            //    {
                            //        //extract scanned text lines here
                            //        lines = lines + line.Value + "\n";
                            //        foreach (IText element in line.Components)
                            //        {
                            //            //extract scanned text words here
                            //            words = words + element.Value + ", ";
                            //        }
                            //    }
                            //}
                            //if (textBlocks.Size() == 0)
                            //{
                            //    scanResults.Text = "Scan Failed: Found nothing to scan";
                            //}
                            //else
                            //{



                            //    scanResults.Text = "Assim funcaaaaaaaaaaa";
                            //    //scanResults.Text = scanResults.Text + "Blocks: " + "\n";
                            //    //scanResults.Text = scanResults.Text + blocks + "\n";
                            //    //scanResults.Text = scanResults.Text + "---------" + "\n";
                            //    //scanResults.Text = scanResults.Text + "Lines: " + "\n";
                            //    //scanResults.Text = scanResults.Text + lines + "\n";
                            //    //scanResults.Text = scanResults.Text + "---------" + "\n";
                            //    //scanResults.Text = scanResults.Text + "Words: " + "\n";
                            //    //scanResults.Text = scanResults.Text + words + "\n";
                            //    //scanResults.Text = scanResults.Text + "---------" + "\n";
                            //}
                        }
                        //else
                        //{
                        //    scanResults.Text = "Could not set up the detector!";
                        //}
                    }
                }
                catch (System.Exception e)
                {
                    Log.Error("OnActivityResult", e.StackTrace);
                }
            }
        }