/// <summary>
 /// This is used to instantiate the converter based on the type
 /// of the <c>Convert</c> annotation provided. If the type
 /// can not be instantiated for some reason then an exception is
 /// thrown from this method.
 /// </summary>
 /// <param name="convert">
 /// this is the annotation containing the type
 /// </param>
 /// <returns>
 /// this returns an instance of the provided type
 /// </returns>
 public Converter GetInstance(Convert convert) {
    Class type = convert.value();
    if(type.isInterface()) {
       throw new ConvertException("Can not instantiate %s", type);
    }
    return GetInstance(type);
 }
Exemple #2
0
 public static void print_conversions(Convert converter, Convert.Units[] units, double magnitude, Convert.Units from)
 {
     foreach (Convert.Units to in units) {
         double conversion = converter.convert (magnitude, from, to);
         Console.WriteLine (magnitude + " " + from + "(s)" + " = " + " " + conversion.ToString () + " " + to + "(s)");
     }
 }
 static void Main()
 {
     Convert myTemp = new Convert();
     Console.WriteLine("Please insesrt your temp in Celsius:");
     var temp = (float)Convert.ToDouble(System.Console.ReadLine());
     var tempinKelvin = myTemp.ConvertToKelvin(temp);
     Console.WriteLine("Your tempreture in Kelvin is:{0}", tempinKelvin);
 }
 protected void ConvertButton_Click(object sender, EventArgs e)
 {
     Convert wsConvert = new Convert();
     double temperature =
         System.Convert.ToDouble(TemperatureTextBox.Text);
     FahrenheitLabel.Text = "Fahrenheit To Celsius = " +
         wsConvert.FahrenheitToCelsius(temperature).ToString();
     CelsiusLabel.Text = "Celsius To Fahrenheit = " +
         wsConvert.CelsiusToFahrenheit(temperature).ToString();
 }
Exemple #5
0
        public ConvertResponse Post(Convert request)
        {
            ConvertResponse response = new ConvertResponse();

            if (request.FromFormat == null)
                request.FromFormat = FormatType.Tson.ToString();

            FormatType toFormat = (FormatType)Enum.Parse(typeof(FormatType), request.ToFormat, ignoreCase: true);
            FormatType fromFormat;

            if (String.IsNullOrEmpty(request.FromFormat))
                fromFormat = FormatType.Tson;
            else
                fromFormat = (FormatType)Enum.Parse(typeof(FormatType), request.FromFormat, ignoreCase: true);

            if (fromFormat == FormatType.Tson)
            {
                switch (toFormat)
                {
                case FormatType.Json:
                    response.Data = Tson.ToJson(request.Data);
                    break;
                case FormatType.Jsv:
                    response.Data = Tson.ToJsv(request.Data);
                    break;
                case FormatType.Xml:
                    response.Data = Tson.ToXml(request.Data);
                    break;
                case FormatType.Tson:
                    response.Data = request.Data;
                    break;
                }
            }
            else if (fromFormat == FormatType.Json)
            {
                if (toFormat != FormatType.Tson)
                    throw new NotSupportedException();

                response.Data = new TsonJTokenNodeVisitor(JObject.Parse(request.Data)).ToTson();
            }

            return response;
        }
Exemple #6
0
        public static void Main(string[] args)
        {
            Convert converter = new Convert ();

            while (true) {
                try {

                    Console.WriteLine ("\nInput category: length, volume or area");
                    String category = Console.ReadLine ().ToLower ().Trim ();

                    Console.WriteLine ("Input magnitude, e.g.: 1, 234, 23423");
                    String mag_input = Console.ReadLine ().ToLower().Trim();
                    double magnitude = Double.Parse (mag_input);

                    Console.WriteLine ("Input unit, e.g.: feet, meter, mile, liter, ounce, quart, sqmile, sqfeet, acre");
                    String from_unit_string = Console.ReadLine ().ToLower().Trim();

                    Convert.Units from = converter.ParseUnitsString (from_unit_string);

                    switch (category) {
                    case Units.LENGTH:
                        converter.SetConvertStrategy (new LengthStrategy ());
                        print_conversions (converter, LengthStrategy.Conversions, magnitude, from);
                        break;
                    case Units.VOLUME:
                        converter.SetConvertStrategy (new VolumeStrategy ());
                        print_conversions (converter, VolumeStrategy.Conversions, magnitude, from);
                        break;
                    case Units.AREA:
                        converter.SetConvertStrategy (new AreaStrategy ());
                        print_conversions (converter, AreaStrategy.Conversions, magnitude, from);
                        break;
                    default:
                        break;
                    }
                } catch (Exception) {
                    Console.WriteLine ("\nInput error, restarting...\n");
                }
            }//end while
        }
        public override double convert(double magnitude, Convert.Units from, Convert.Units to)
        {
            if (from == Convert.Units.SquareFeet && to == Convert.Units.SquareMile) {
                return sqfeet_to_sqmiles (magnitude);
            } else if (from == Convert.Units.SquareFeet && to == Convert.Units.Acre) {
                return sqfeet_to_acres (magnitude);
            } else if (from == Convert.Units.SquareMile && to == Convert.Units.SquareFeet) {
                return sqmiles_to_sqfeet (magnitude);
            } else if (from == Convert.Units.SquareMile && to == Convert.Units.Acre) {
                return sqmiles_to_acres (magnitude);
            } else if (from == Convert.Units.Acre && to == Convert.Units.SquareFeet) {
                return acres_to_sqfeet (magnitude);
            } else if (from == Convert.Units.Acre && to == Convert.Units.SquareMile) {
                return acres_to_sqmiles (magnitude);
            } else if (from == to)
            {
                return magnitude;
            }

            //no conversion possible
            throw new Exception("cannot find conversion stragety for this area unit");
        }
        //ounces, quarts and liters
        public override double convert(double magnitude, Convert.Units from, Convert.Units to)
        {
            if (from == Convert.Units.Ounce && to == Convert.Units.Liter) {
                return ounces_to_liters (magnitude);
            } else if (from == Convert.Units.Ounce && to == Convert.Units.Quart) {
                return ounces_to_quarts (magnitude);
            } else if (from == Convert.Units.Quart && to == Convert.Units.Ounce) {
                return quarts_to_ounces (magnitude);
            } else if (from == Convert.Units.Quart && to == Convert.Units.Liter) {
                return quarts_to_liters (magnitude);
            } else if (from == Convert.Units.Liter && to == Convert.Units.Ounce) {
                return liters_to_ounces (magnitude);
            } else if (from == Convert.Units.Liter && to == Convert.Units.Quart) {
                return liters_to_quarts (magnitude);
            } else if (from == to)
            {
                return magnitude;
            }

            //no conversion possible
            throw new Exception("cannot find conversion stragety for this volume unit");
        }
        //implement interface
        public override double convert(double magnitude, Convert.Units from, Convert.Units to)
        {
            if (from == Convert.Units.Feet && to == Convert.Units.Meter) {
                return feet_to_meters (magnitude);
            } else if (from == Convert.Units.Feet && to == Convert.Units.Mile) {
                return feet_to_miles (magnitude);
            } else if (from == Convert.Units.Meter && to == Convert.Units.Feet) {
                return meters_to_feet (magnitude);
            } else if (from == Convert.Units.Meter && to == Convert.Units.Mile) {
                return meters_to_miles (magnitude);
            } else if (from == Convert.Units.Mile && to == Convert.Units.Feet) {
                return miles_to_feet (magnitude);
            } else if (from == Convert.Units.Mile && to == Convert.Units.Meter) {
                return miles_to_meters (magnitude);
            } else if (from == to)
            {
                return magnitude;
            }

            //no conversion possible
            throw new Exception("cannot find conversion stragety for this length unit");
        }
        public static void ConvertToIBAN()
        {
            foreach (Excel.Range cell in AccountNumber.Range.Cells)
            {
                bool blnContinue = true;
                string strValue = "";

                try
                {
                    double num = (double)cell.Value;
                    strValue = num.ToString();
                }
                catch (Exception ex)
                {
                    try
                    {
                        cell.AddComment("Cell value is not a numeric value / accountnumber");
                    }
                    catch (Exception) { }
                    blnContinue = false;
                }

                if (blnContinue)
                {
                    convert = new Convert(strValue);

                    if (convert.Check())
                    {
                        if (convert.ToIBAN())
                        {
                            cell.Value = convert.IBAN;
                        }
                    }
                }

            }
        }
Exemple #11
0
        private static void ProcessPosition(GPSPosition position)
        {
            //last_point = new GPSPoint(position.Time.ToUniversalTime(), (float)position.dblLatitude, (float)position.dblLongitude, Convert.ToInt32(position.flSpeed))
            last_point = new GPSPoint(position.Time, (float)position.dblLatitude, (float)position.dblLongitude, Convert.ToInt32(position.flSpeed))
            {
                Course = position.flHeading
            };

            T.INFO(last_point.ToString());
            double delta_distance = -1;

            mobile.Fix(last_point);

            if (destination_point != null)
            {
                delta_distance = Distances.Rhumb(last_point, destination_point);
                T.TRACE(String.Format("TRACKER: delta_distance={0}", delta_distance));
                //Locked = delta_distance <= destination_area_radio;

                /*if (delta_distance <= destination_radio)
                 * {
                 *  T.INFO("TRACKER: Llegamos al destino. Informando.");
                 *  Beep("gps_in_destination");
                 *  posicion.Clear();
                 *  destination_point = null;
                 *  var dummy = new byte[2];
                 *  dummy[0] = 0;
                 *  posicion.Push(last_point.AsMessage((int)delta_distance), dummy);
                 *  mobile.ActiveOT(last_point, active_ot);
                 * }*/
            }

            if (last_sent_point == null || (last_point.Date - last_sent_point.Date).TotalSeconds >= fix_interval)
            {
                T.INFO("TRACKER: fix seleccionado para enviar.");
                last_sent_point = last_point;
                mobile.Fix(last_sent_point);
                posicion.Clear();
                var dummy = new byte[2];
                dummy[0] = 0;
                posicion.Push(last_sent_point.AsMessage((int)delta_distance), dummy);
            }
        }
Exemple #12
0
        /// <summary>
        /// 查询的数据
        /// </summary>
        /// <param name="SysEntities">数据访问的上下文</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc(默认)还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <param name="listQuery">额外的参数</param>
        /// <returns></returns>
        public IQueryable <COST_PayTemporary> GetData(SysEntities db, string order, string sort, string search, params object[] listQuery)
        {
            string where = string.Empty;
            int flagWhere = 0;

            Dictionary <string, string> queryDic = ValueConvert.StringToDictionary(search.GetString());

            if (queryDic != null && queryDic.Count > 0)
            {
                foreach (var item in queryDic)
                {
                    if (flagWhere != 0)
                    {
                        where += " and ";
                    }
                    flagWhere++;


                    if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value) && item.Key.Contains(Start_Time)) //开始时间
                    {
                        where += "it.[" + item.Key.Remove(item.Key.IndexOf(Start_Time)) + "] >=  CAST('" + item.Value + "' as   System.DateTime)";
                        continue;
                    }
                    if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value) && item.Key.Contains(End_Time)) //结束时间+1
                    {
                        where += "it.[" + item.Key.Remove(item.Key.IndexOf(End_Time)) + "] <  CAST('" + Convert.ToDateTime(item.Value).AddDays(1) + "' as   System.DateTime)";
                        continue;
                    }
                    if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value) && item.Key.Contains(Start_Int)) //开始数值
                    {
                        where += "it.[" + item.Key.Remove(item.Key.IndexOf(Start_Int)) + "] >= " + item.Value.GetInt();
                        continue;
                    }
                    if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value) && item.Key.Contains(End_Int)) //结束数值
                    {
                        where += "it.[" + item.Key.Remove(item.Key.IndexOf(End_Int)) + "] <= " + item.Value.GetInt();
                        continue;
                    }

                    if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value) && item.Key.Contains(DDL_Int)) //精确查询数值
                    {
                        where += "it.[" + item.Key.Remove(item.Key.IndexOf(DDL_Int)) + "] =" + item.Value;
                        continue;
                    }
                    if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value) && item.Key.Contains(DDL_String)) //精确查询字符串
                    {
                        where += "it.[" + item.Key.Remove(item.Key.IndexOf(DDL_String)) + "] = '" + item.Value + "'";
                        continue;
                    }
                    where += "it.[" + item.Key + "] like '%" + item.Value + "%'";//模糊查询
                }
            }
            return(((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext
                   .CreateObjectSet <COST_PayTemporary>().Where(string.IsNullOrEmpty(where) ? "true" : where)
                   .OrderBy("it.[" + sort.GetString() + "] " + order.GetString())
                   .AsQueryable());
        }
        private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
        {
            ApiDescription apiDescription = apiModel.ApiDescription;
            foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
            {
                if (apiParameter.Source == ApiParameterSource.FromUri)
                {
                    HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
                    Type parameterType = null;
                    ModelDescription typeDescription = null;
                    ComplexTypeModelDescription complexTypeDescription = null;
                    if (parameterDescriptor != null)
                    {
                        parameterType = parameterDescriptor.ParameterType;
                        typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
                        complexTypeDescription = typeDescription as ComplexTypeModelDescription;
                    }

                    // Example:
                    // [TypeConverter(typeof(PointConverter))]
                    // public class Point
                    // {
                    //     public Point(int x, int y)
                    //     {
                    //         X = x;
                    //         Y = y;
                    //     }
                    //     public int X { get; set; }
                    //     public int Y { get; set; }
                    // }
                    // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
                    // 
                    // public class Point
                    // {
                    //     public int X { get; set; }
                    //     public int Y { get; set; }
                    // }
                    // Regular complex class Point will have properties X and Y added to UriParameters collection.
                    if (complexTypeDescription != null
                        && !IsBindableWithTypeConverter(parameterType))
                    {
                        foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
                        {
                            apiModel.UriParameters.Add(uriParameter);
                        }
                    }
                    else if (parameterDescriptor != null)
                    {
                        ParameterDescription uriParameter =
                            AddParameterDescription(apiModel, apiParameter, typeDescription);

                        if (!parameterDescriptor.IsOptional)
                        {
                            uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
                        }

                        object defaultValue = parameterDescriptor.DefaultValue;
                        if (defaultValue != null)
                        {
                            uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
                        }
                    }
                    else
                    {
                        Debug.Assert(parameterDescriptor == null);

                        // If parameterDescriptor is null, this is an undeclared route parameter which only occurs
                        // when source is FromUri. Ignored in request model and among resource parameters but listed
                        // as a simple string here.
                        ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
                        AddParameterDescription(apiModel, apiParameter, modelDescription);
                    }
                }
            }
        }
Exemple #14
0
 public void setAge (string args)
 {
     string optValue = JsonHelper.Deserialize<string[]>(args)[0];
     MobileAppTracker.Instance.SetAge(Convert.ToInt32(optValue));
     DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "setAge succeeded"));
 }
Exemple #15
0
        public void ConfigureServices(IServiceCollection services)
        {
            X509Certificate2 cert;

            //if (Environment.IsProduction())
            //{
            //    // Azure deployment, will be used if deployed to Azure
            //    var vaultConfigSection = Configuration.GetSection("Vault");
            //    var keyVaultService = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
            //    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
            //}
            //else
            //{
            var base64EncodedStr = Convert.FromBase64String(Configuration["STSCertificate"]);

            cert = new X509Certificate2(base64EncodedStr, string.Empty, X509KeyStorageFlags.MachineKeySet);
            //}

            services.Configure<StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddSingleton<LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.Configure<RequestLocalizationOptions>(
               options =>
               {
                   var supportedCultures = new List<CultureInfo>
                       {
                            new CultureInfo("en-US"),
                            new CultureInfo("de-DE"),
                            new CultureInfo("de-CH"),
                            new CultureInfo("it-IT"),
                            new CultureInfo("gsw-CH"),
                            new CultureInfo("fr-FR")
                       };

                   options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                   options.SupportedCultures = supportedCultures;
                   options.SupportedUICultures = supportedCultures;

                   var providerQuery = new LocalizationQueryProvider
                   {
                       QureyParamterName = "ui_locales"
                   };

                   options.RequestCultureProviders.Insert(0, providerQuery);
               });

            services.Configure<IISOptions>(options =>
            {
                options.AutomaticAuthentication = false;
                options.AuthenticationDisplayName = "Windows";
            });

            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            // Add framework services.
            services.AddDbContextPool<ApplicationDbContext>(options =>
            {
                options.UseSqlite(connectionString);
                options.UseSqlite(connectionString, b => b.MigrationsAssembly(migrationsAssembly));
            });

            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", corsBuilder =>
                {
                    corsBuilder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin()
                    .AllowCredentials();
                });
            });

            services.AddTransient<ISeedData, SeedData>();
            services.AddTransient<IProfileService, CustomProfileService>();
            services.AddTransient<ApplicationDbContext>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                           .AddViewLocalization()
                           .AddDataAnnotationsLocalization(options =>
                           {
                               options.DataAnnotationLocalizerProvider = (type, factory) =>
                               {
                                   var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                                   return factory.Create("SharedResource", assemblyName.Name);
                               };
                           });

            services.AddTransient<IProfileService, CustomProfileService>();

            services.AddTransient<IEmailSender, EmailSender>();

            var identityServer = services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseSuccessEvents = true;
                })
                .AddSigningCredential(cert)
                // this adds the config data from DB (clients, resources, CORS)
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlite(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                })

                // OR In memory config store
                //.AddInMemoryApiResources(Config.GetApiResources())
                //.AddInMemoryClients(Config.GetClients(Configuration["ClientUrls"]))
                //.AddInMemoryIdentityResources(Config.GetIdentityResources())

                // this adds the operational data from DB (codes, tokens, consents)
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlite(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));

                    // this enables automatic token cleanup. this is optional.
                    options.EnableTokenCleanup = true;
                    // options.TokenCleanupInterval = 15; // interval in seconds. 15 seconds useful for debugging
                })
                .AddAspNetIdentity<ApplicationUser>()
                .AddProfileService<CustomProfileService>();

            services.AddAuthentication()
               .AddGoogle(options =>
               {
                   options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                   options.ClientId = "476611152863-ltgqfk9jhq1vsenin5039n58ogkraltb.apps.googleusercontent.com";
                   options.ClientSecret = "rSHvhgdOQUB4KMc5JS1alzhg";
               })
               .AddOpenIdConnect("aad", "Login with Azure AD", options =>
                {
                    options.Authority = $"https://login.microsoftonline.com/common";
                    options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false };
                    options.ClientId = "99eb0b9d-ca40-476e-b5ac-6f4c32bfb530";
                    options.CallbackPath = "/signin-oidc";
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                });
        }
 public abstract double convert(double magnitude, Convert.Units from, Convert.Units to);
 /// <summary>
 /// Converts base 64 string to a byte array
 /// </summary>
 /// <param name="Input">Input string</param>
 /// <returns>A byte array equivalent of the base 64 string</returns>
 public static byte[] FromBase64(this string Input)
 {
     return string.IsNullOrEmpty(Input) ? new byte[0] : Convert.FromBase64String(Input);
 }
        protected void level_Clicked(object sender, EventArgs e)
        {
            ImageButton btn   = sender as ImageButton;
            string      level = btn.ID.Substring(3, 1);

            SqlConnection con = new SqlConnection(connString);

            con.Open();

            SqlCommand get = new SqlCommand("SELECT LevelID From Levels WHERE LevelNumber = @num AND ClassID = @ID", con);

            get.Parameters.AddWithValue("@num", Convert.ToInt32(level));
            get.Parameters.AddWithValue("@ID", Convert.ToInt32(Session["CLASSID"]));
            int levelID = Convert.ToInt32(get.ExecuteScalar());

            SqlCommand checkLevel = new SqlCommand("SELECT 5 FROM Unlocking WHERE StudID = @stud AND ClassID = @class AND LevelID < @level", con);

            checkLevel.Parameters.AddWithValue("@stud", Convert.ToInt32(Session["StudentID"]));
            checkLevel.Parameters.AddWithValue("@level", levelID);
            checkLevel.Parameters.AddWithValue("@class", Convert.ToInt32(Session["CLASSID"]));
            SqlDataReader dro = checkLevel.ExecuteReader();

            if (!dro.HasRows && levelID - 1 == 0)
            {
                dro.Close();
                Response.Write("<script type='text/javascript'>alert('This level is still locked!!!');</script>");
                return;
            }
            dro.Close();
            SqlCommand cmd = new SqlCommand("SELECT VideoLink From Levels WHERE LevelNumber = @num AND ClassID = @ID", con);

            cmd.Parameters.AddWithValue("@num", Convert.ToInt32(level));
            cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(Session["CLASSID"]));
            string videolink = cmd.ExecuteScalar().ToString();

            Session["VIDEOLINK"] = videolink;

            Session["LEVELID"] = levelID;

            SqlCommand check = new SqlCommand("SELECT 55 FROM Unlocking WHERE StudID = @stud AND ClassID = @class AND LevelID = @level", con);

            check.Parameters.AddWithValue("@stud", Convert.ToInt32(Session["StudentID"]));
            check.Parameters.AddWithValue("@level", Convert.ToInt32(Session["LEVELID"]));
            check.Parameters.AddWithValue("@class", Convert.ToInt32(Session["CLASSID"]));
            SqlDataReader dr = check.ExecuteReader();

            if (!dr.HasRows)
            {
                dr.Close();
                SqlCommand deleteprev = new SqlCommand("DELETE FROM Unlocking WHERE StudID = @stud AND ClassID = @class", con);
                deleteprev.Parameters.AddWithValue("@stud", Convert.ToInt32(Session["StudentID"]));
                deleteprev.Parameters.AddWithValue("@class", Convert.ToInt32(Session["CLASSID"]));
                deleteprev.ExecuteNonQuery();
                SqlCommand watch = new SqlCommand("INSERT INTO Unlocking VALUES (" + Session["StudentID"].ToString() + "," + Session["CLASSID"].ToString() + "," + Convert.ToInt32(Session["LEVELID"]) + ")", con);
                watch.ExecuteNonQuery();
            }

            con.Close();

            Response.Write("<script type='text/javascript'>window.open('" + Session["VIDEOLINK"] + "','_blank');</script>");

            Response.Write("<script type='text/javascript'>alert('You have completed Level " + level + " of this class!');</script>");
        }
        protected void selectClass_Click(object sender, EventArgs e)
        {
            visibleAll();

            Button btn = sender as Button;
            Label  lbl = (Label)btn.Parent.Parent.Controls[1].Controls[1];

            Session["CLASSNAME"] = lbl.Text;
            classname.Text       = Session["CLASSNAME"].ToString();

            //check number of levels
            SqlConnection con = new SqlConnection(connString);

            con.Open();
            Label lbo = (Label)btn.Parent.Parent.Controls[0].Controls[1];

            Session["CLASSID"] = lbo.Text;
            SqlCommand sql = new SqlCommand("SELECT COUNT(*) FROM Levels WHERE ClassID = @ID", con);

            sql.Parameters.AddWithValue("@ID", Convert.ToInt32(Session["CLASSID"]));
            int levelCount = Convert.ToInt32(sql.ExecuteScalar());

            con.Close();

            switch (levelCount)
            {
            case 1:
            {
                btn2.Visible = false;
                goto case 2;
            }

            case 2:
            {
                btn3.Visible = false;
                goto case 3;
            }

            case 3:
            {
                btn4.Visible = false;
                goto case 4;
            }

            case 4:
            {
                btn5.Visible = false;
                goto case 5;
            }

            case 5:
            {
                btn6.Visible = false;
                goto case 6;
            }

            case 6:
            {
                btn7.Visible = false;
                goto case 7;
            }

            case 7:
            {
                btn8.Visible = false;
                goto default;
            }

            default: break;
            }
            GamePanel.Visible = true;
        }
Exemple #20
0
        //cập nhật NVKD khi chọn mặt hàng
        //        private void LayNVKD2(DataRow drCT)
        //        {
        //            RepositoryItemGridLookUpEdit gluHH = gcMain.RepositoryItems["Description"] as RepositoryItemGridLookUpEdit;
        //            if (gluHH.OwnerEdit != null && gluHH.OwnerEdit.IsPopupOpen)
        //                return;
        //            if (gluKH.EditValue == null || gluKH.EditValue.ToString() == "")
        //                return;
        //            BindingSource bs = gluKH.Properties.DataSource as BindingSource;
        //            if (bs == null || bs.DataSource.GetType() != typeof(DataTable))
        //                return;
        //            DataTable dt = bs.DataSource as DataTable;
        //            DataRow[] drs = dt.Select("MaKH = '" + gluKH.EditValue.ToString() + "'");
        //            if (drs.Length == 0)
        //                return;
        //            DataRow drKH = drs[0];
        //            if (drKH == null)
        //                return;
        //            string pl = drKH["Nhom1"].ToString();
        //            if (pl == "")
        //            {
        //                XtraMessageBox.Show("Khách hàng này chưa phân loại, không thể tính doanh số cho salesman!",
        //                    Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
        //                drCT["NVKD"] = DBNull.Value;
        //                return;
        //            }
        //            string kv = drKH["KhuVuc"].ToString();
        //            if (kv == "")
        //            {
        //                XtraMessageBox.Show("Khách hàng này chưa phân khu vực, không thể tính doanh số cho salesman!",
        //                    Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
        //                drCT["NVKD"] = DBNull.Value;
        //                return;
        //            }
        //            object mahh = drCT["Description"];
        //            bs = gluHH.DataSource as BindingSource;
        //            if (bs == null || bs.DataSource.GetType() != typeof(DataTable))
        //                return;
        //            dt = bs.DataSource as DataTable;
        //            drs = dt.Select("PNo = '" + mahh.ToString() + "'");
        //            if (drs.Length == 0)
        //                return;
        //            DataRow drHH = drs[0];
        //            string nhom = drHH["Nhom"].ToString();
        //            if (nhom == "")
        //            {
        //                XtraMessageBox.Show("Mặt hàng " + drHH["TenVT2"].ToString() + " chưa phân nhóm, không thể tính doanh số cho salesman!",
        //                    Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
        //                drCT["NVKD"] = DBNull.Value;
        //                return;
        //            }
        //            dt = db.GetDataTable(string.Format(@"select MaNV from NVKDTheoKV where (DMTP like '{0},%' or DMTP like '%,{0}' or DMTP like '%,{0},%' or DMTP = '{0}') 
        //                    and (NhomKH like '{1},%' or NhomKH like '%,{1}' or NhomKH like '%,{1},%' or NhomKH = '{1}')
        //                    and (NhomVT like '{2},%' or NhomVT like '%,{2}' or NhomVT like '%,{2},%' or NhomVT = '{2}')", kv, pl, nhom));
        //            if (dt.Rows.Count == 0)
        //            {
        //                XtraMessageBox.Show(string.Format("Khu vực {0}, loại khách hàng {1} và nhóm hàng {2} hiện chưa phân sales", kv, pl, nhom),
        //                    Config.GetValue("PackageName").ToString());
        //                drCT["NVKD"] = DBNull.Value;
        //                return;
        //            }
        //            if (dt.Rows.Count > 1)
        //            {
        //                XtraMessageBox.Show(string.Format("Khu vực {0}, loại khách hàng {1} và nhóm hàng {2} hiện đang phân nhiều sales cùng lúc", kv, pl, nhom),
        //                    Config.GetValue("PackageName").ToString());
        //                drCT["NVKD"] = DBNull.Value;
        //                return;
        //            }
        //            drCT["NVKD"] = dt.Rows[0]["MaNV"];
        //        }

        //tính khi thay đổi hàng hóa hoặc phụ kiện
        private void TinhGiaCoDinh2(DataRow drCT, string cl)
        {
            RepositoryItemGridLookUpEdit gluHH = gcMain.RepositoryItems[cl] as RepositoryItemGridLookUpEdit;
            RepositoryItemGridLookUpEdit gluPK = gcMain.RepositoryItems["MaVT2"] as RepositoryItemGridLookUpEdit;
            if (gluHH.OwnerEdit != null && gluHH.OwnerEdit.IsPopupOpen)
                return;
            if (gluKH.EditValue == null || gluKH.EditValue.ToString() == "")
            {
                XtraMessageBox.Show("Chưa chọn khách hàng, không thể lấy được giá bán!",
                    Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
                return;
            }
            //int n = gluKH.Properties.GetIndexByKeyValue(gluKH.EditValue);
            //if (n < 0)
            //    return;
            BindingSource bs = gluKH.Properties.DataSource as BindingSource;
            if (bs == null || bs.DataSource.GetType() != typeof(DataTable))
                return;
            DataTable dt = bs.DataSource as DataTable;
            DataRow[] drs = dt.Select("MaKH = '" + gluKH.EditValue.ToString() + "'");
            if (drs.Length == 0)
                return;
            DataRow drKH = drs[0];
            if (drKH == null)
                return;
            string pl = drKH["Nhom1"].ToString();
            if (pl == "")
            {
                XtraMessageBox.Show("Khách hàng này chưa phân loại, không thể lấy được giá bán cho khách hàng này!",
                    Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
                return;
            }
            object mahh = drCT[cl];
            //object code = drCT["Description"];
            bs = gluHH.DataSource as BindingSource;
            if (bs == null || bs.DataSource.GetType() != typeof(DataTable))
                return;
            dt = bs.DataSource as DataTable;
            drs = dt.Select("MaVT = '" + mahh.ToString() + "' or PNo = '" + mahh.ToString() + "'");
            if (drs.Length == 0)
                return;
            DataRow drHH = drs[0];
            string nhom = drHH["Nhom"].ToString();
            if (nhom == "")
                XtraMessageBox.Show("Mặt hàng " + drHH["TenVT2"].ToString() + " chưa phân nhóm, có thể ảnh hưởng đến cách tính giá bán!",
                    Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
            object mapk = drCT["MaVT2"];
            int k = gluPK.GetIndexByKeyValue(mapk);
            DataRow drPK = null;
            if (k >= 0)
                drPK = gluPK.View.GetDataRow(k);
            object ghh, gpk;
            switch (pl)
            {
                case "OEM":
                case "TRA":
                    ghh = drHH == null ? 0 : drHH["GiaOME"];
                    gpk = drPK == null ? 0 : drPK["GiaOME"];
                    break;
                case "DIS":
                    ghh = drHH == null ? 0 : drHH["GiaDTB"];
                    gpk = drPK == null ? 0 : drPK["GiaDTB"];
                    break;
                default:
                    ghh = drHH == null ? 0 : drHH["GiaBan"];
                    gpk = drPK == null ? 0 : drPK["GiaBan"];
                    break;
            }
            if (cl == "Description")
            {
                string dvt = drCT["MaDVT"].ToString();
                if (dvt == "")      //chua co dvt thi chua tinh gia ban
                    return;
                drCT["GiaGoc"] = ghh;
                decimal gg = decimal.Parse(drCT["GiaGoc"].ToString());
                #region Cách tính cũ
                //if (drHH["MaDVT"].ToString() != "7") //mã của dvt m2
                //    drCT["Gia"] = gg;
                //else
                //{
                //    decimal r = decimal.Parse(drCT["Rong"].ToString());
                //    decimal d = decimal.Parse(drCT["Cao"].ToString());
                //    if (nhom == "HPFB" || nhom == "SB")
                //        drCT["Gia"] = r == 0 ? gg : (r * (d + 100) / 1000000) * gg;
                //    else
                //        drCT["Gia"] = r == 0 ? gg : (r * d / 1000000) * gg;
                //}
                #endregion
                decimal sl = decimal.Parse(drCT["SoLuong"].ToString());
                if (nhom == "FB" || nhom == "SB")
                {
                    decimal d = decimal.Parse(drCT["Cao"].ToString());
                    decimal r = decimal.Parse(drCT["Rong"].ToString());
                    decimal t = Convert.ToDecimal(drCT["PE"]) + Convert.ToDecimal(drCT["HS"]) + Convert.ToDecimal(drCT["AT"]);
                    if (t > 0)
                        d = (nhom == "SB") ? d + 120 : d + 80;
                    if (dvt == "7")   //m2
                    {
                        drCT["Ps"] = (d * r) / 1000000 * gg;
                        if (sl > 0)
                            drCT["Gia"] = Convert.ToDecimal(drCT["Ps"]) / sl;
                        else
                            drCT["Gia"] = 0;
                    }
                    else
                        if (dvt == "10")  //m
                        {
                            drCT["Ps"] = (d * r) / 1000000 * gg;
                            if (d > 0)
                                drCT["Gia"] = Convert.ToDecimal(drCT["Ps"]) / d * 1000;
                            else
                                drCT["Gia"] = 0;
                        }
                        else
                        {
                            drCT["Ps"] = (d * r) / 1000000 * gg * sl;
                            if (sl > 0)
                                drCT["Gia"] = Convert.ToDecimal(drCT["Ps"]) / sl;
                            else
                                drCT["Gia"] = 0;
                        }
                }
                else
                {
                    drCT["Gia"] = gg;
                    drCT["Ps"] = decimal.Parse(drCT["Gia"].ToString()) * sl;
                }
            }
            else
            {
                drCT["DGPKGoc"] = gpk;
                decimal gg = decimal.Parse(drCT["DGPKGOC"].ToString());
                if (drPK["MaDVT"].ToString() != "7") //mã của dvt m2
                    drCT["DGPK"] = gg;
                else
                {
                    decimal r = decimal.Parse(drCT["RongPK"].ToString());
                    decimal d = decimal.Parse(drCT["CaoPK"].ToString());
                    drCT["DGPK"] = r == 0 ? gg : (r * d / 1000000) * gg;
                }
            }
        }
Exemple #21
0
        //void gluKH_CloseUp(object sender, DevExpress.XtraEditors.Controls.CloseUpEventArgs e)
        //{
        //    if (data.BsMain == null || data.BsMain.Current == null)
        //        return;
        //    DataRowView drv = data.BsMain.Current as DataRowView;
        //    if (drv.Row.RowState == DataRowState.Deleted ||
        //        drv.Row.RowState == DataRowState.Unchanged)
        //        return;
        //    if (e.AcceptValue && e.CloseMode == PopupCloseMode.Normal)
        //    {
        //        //tính đơn giá cố định
        //        TinhGiaCoDinh1();
        //        LayNVKD1();
        //    }
        //}

        void TinhChiPhi_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Row.RowState == DataRowState.Deleted)
                return;
            try
            {
                string cn = e.Column.ColumnName.ToUpper();
                //tính đơn giá cố định theo phân loại khách hàng + tính đơn giá hàng hóa phụ kiện
                //if (cn.Equals("DESCRIPTION"))
                //    LayNVKD2(e.Row);
                if (cn == "DESCRIPTION" || cn == "DAI" || cn == "RONG" || cn == "CAO" || cn == "MADVT" || cn == "SOLUONG"
                     || cn == "PE" || cn == "HS" || cn == "AT")
                    TinhGiaCoDinh2(e.Row, "Description");
                if (cn == "MAVT2" || cn == "DAIPK" || cn == "RONGPK" || cn == "CAOPK")
                    TinhGiaCoDinh2(e.Row, "MaVT2");

                //tính chi phí
                string nhom = e.Row["Nhom"].ToString();
                if (e.Column.ColumnName.ToUpper().Equals("HP") || e.Column.ColumnName.ToUpper().Equals("HS")
                    || e.Column.ColumnName.ToUpper().Equals("FT") || e.Column.ColumnName.ToUpper().Equals("AT"))
                {
                    decimal TT = 0, SL = 0;
                    if (decimal.Parse(e.Row[e.Column].ToString()) != 0 && nhom == "")
                        XtraMessageBox.Show("Mặt hàng này chưa phân nhóm, sẽ không tính được chi phí công nối!",
                            Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
                    if (nhom == "SB")
                    {
                        if (e.Column.ColumnName.ToUpper().Equals("HS"))
                        {
                            SL = decimal.Parse(e.Row["HS"].ToString());
                            TT = SL * 500;
                            TT = Math.Max(TT, 10000);
                            e.Row["TTHS"] = SL == 0 ? 0 : TT;
                        }
                        if (e.Column.ColumnName.ToUpper().Equals("FT"))
                        {
                            SL = decimal.Parse(e.Row["FT"].ToString());
                            TT = SL * 1000;
                            TT = Math.Max(TT, 10000);
                            e.Row["TTFT"] = SL == 0 ? 0 : TT;
                        }
                        if (e.Column.ColumnName.ToUpper().Equals("AT"))
                        {
                            SL = decimal.Parse(e.Row["AT"].ToString());
                            TT = SL * 500;
                            TT = Math.Max(TT, 10000);
                            e.Row["TTAT"] = SL == 0 ? 0 : TT;
                            //cong them 1 trieu vao chi phi van chuyen
                            if (data.BsMain.Current != null)
                            {
                                DataRow drMaster = (data.BsMain.Current as DataRowView).Row;
                                object oat = e.Row.Table.Compute("sum(AT)", "MT63ID = '" + drMaster["MT63ID"].ToString() + "'");
                                drMaster["CPVC"] = Convert.ToDecimal(oat) > 0 ? 1000000 : 0;
                            }
                        }
                        if (e.Column.ColumnName.ToUpper().Equals("HP"))
                        {
                            SL = decimal.Parse(e.Row["HP"].ToString());
                            TT = SL * 1000000;
                            e.Row["TTOP"] = SL == 0 ? 0 : TT;
                        }

                    }
                    else if (nhom == "FB")
                    {
                        if (e.Column.ColumnName.ToUpper().Equals("HS"))
                        {
                            SL = decimal.Parse(e.Row["HS"].ToString());
                            TT = SL * 1000;
                            TT = Math.Max(TT, 10000);
                            e.Row["TTHS"] = SL == 0 ? 0 : TT;
                        }
                        if (e.Column.ColumnName.ToUpper().Equals("FT"))
                        {
                            SL = decimal.Parse(e.Row["FT"].ToString());
                            TT = SL * 1000;
                            TT = Math.Max(TT, 10000);
                            e.Row["TTFT"] = SL == 0 ? 0 : TT;
                        }
                        if (e.Column.ColumnName.ToUpper().Equals("AT"))
                        {
                            SL = decimal.Parse(e.Row["AT"].ToString());
                            TT = SL * 1000;
                            TT = Math.Max(TT, 10000);
                            e.Row["TTAT"] = SL == 0 ? 0 : TT;
                            //cong them 1 trieu vao chi phi van chuyen
                            if (data.BsMain.Current != null)
                            {
                                DataRow drMaster = (data.BsMain.Current as DataRowView).Row;
                                object oat = e.Row.Table.Compute("sum(AT)", "MT63ID = '" + drMaster["MT63ID"].ToString() + "'");
                                drMaster["CPVC"] = Convert.ToDecimal(oat) > 0 ? 1000000 : 0;
                            }
                        }
                        if (e.Column.ColumnName.ToUpper().Equals("HP"))
                        {
                            SL = decimal.Parse(e.Row["HP"].ToString());
                            TT = SL * 1000000;
                            e.Row["TTOP"] = SL == 0 ? 0 : TT;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Cập nhật đơn giá và chi phí: " + ex.Message, Config.GetValue("PackageName").ToString(), MessageBoxButtons.OK);
            }
        }
Exemple #22
0
        public override void Use(Player p, string message)
        {
            Player who = null;

            if (message == "")
            {
                who = p; message = p.name;
            }
            else
            {
                who = Player.Find(message);
            }
            if (who != null && !who.hidden)
            {
                Player.SendMessage(p, who.color + who.name + Server.DefaultColor + " is on &b" + who.level.name);
                Player.SendMessage(p, who.color + who.prefix + who.name + Server.DefaultColor + " has :");
                Player.SendMessage(p, "> > the rank of " + who.group.color + who.group.name);
                try
                {
                    if (!Group.Find("Nobody").commands.Contains("pay") && !Group.Find("Nobody").commands.Contains("give") && !Group.Find("Nobody").commands.Contains("take"))
                    {
                        Player.SendMessage(p, "> > &a" + who.money + Server.DefaultColor + " " + Server.moneys);
                    }
                }
                catch { }
                Player.SendMessage(p, "> > &cdied &a" + who.overallDeath + Server.DefaultColor + " times");
                Player.SendMessage(p, "> > &bmodified &a" + who.overallBlocks + Server.DefaultColor + " blocks, &a" + who.loginBlocks + Server.DefaultColor + " since logging in.");
                string storedTime = Convert.ToDateTime(DateTime.Now.Subtract(who.timeLogged).ToString()).ToString("HH:mm:ss");
                Player.SendMessage(p, "> > been logged in for &a" + storedTime);
                Player.SendMessage(p, "> > first logged into the server on &a" + who.firstLogin.ToString("yyyy-MM-dd") + " at " + who.firstLogin.ToString("HH:mm:ss"));
                Player.SendMessage(p, "> > logged in &a" + who.totalLogins + Server.DefaultColor + " times, &c" + who.totalKicked + Server.DefaultColor + " of which ended in a kick.");
                Player.SendMessage(p, "> > " + Awards.awardAmount(who.name) + " awards");

                bool skip = false;
                if (p != null)
                {
                    if (p.group.Permission <= LevelPermission.AdvBuilder)
                    {
                        skip = true;
                    }
                }
                if (!skip)
                {
                    string givenIP;
                    if (Server.bannedIP.Contains(who.ip))
                    {
                        givenIP = "&8" + who.ip + ", which is banned";
                    }
                    else
                    {
                        givenIP = who.ip;
                    }
                    Player.SendMessage(p, "> > the IP of " + givenIP);
                    if (Server.useWhitelist)
                    {
                        if (Server.whiteList.Contains(who.name))
                        {
                            Player.SendMessage(p, "> > Player is &fWhitelisted");
                        }
                    }
                    if (Server.devs.Contains(who.name.ToLower()))
                    {
                        Player.SendMessage(p, Server.DefaultColor + "> > Player is a &9Developer");
                    }
                }
            }
            else
            {
                Player.SendMessage(p, "\"" + message + "\" is offline! Using /whowas instead."); Command.all.Find("whowas").Use(p, message);
            }
        }
		public static Int32 Create(IRSAPIClient proxy, string workspaceName, string templateName)
		{
			try
			{
				int workspaceID = 0;

				//Set the workspace ID
				proxy.APIOptions.WorkspaceID = -1;

				if (templateName == string.Empty)
				{
					throw new SystemException("Template name is blank in your configuration setting. Please add a template name to create a workspace");
				}
				var resultSet = GetArtifactIdOfTemplate(proxy, templateName);

				if (resultSet.Success)
				{
					//Save the artifact ID of the template workspace
					int templateArtifactID = resultSet.Results.FirstOrDefault().Artifact.ArtifactID;

					//Create the workspace DTO
					var workspaceDTO = new kCura.Relativity.Client.DTOs.Workspace();

					//Set primary fields
					//The name of the sample data is being set to a random string so that sample data can be debugged
					//and never causes collisions. You can set this to any string that you want
					workspaceDTO.Name = workspaceName;

					//Get the server id or use the configuration value
					//NOTE: We're using the server ID from the template workspace. This may not be correct and may need to be updatedServerID is hard-coded since we don't have a way to get the server ID.
					int? serverID = resultSet.Results.FirstOrDefault().Artifact.ServerID;

					if (ConfigurationManager.AppSettings.AllKeys.Contains("ServerID"))
					{
						int serverIDConfigValue = Convert.ToInt32(ConfigurationManager.AppSettings["ServerID"]);

						if (serverIDConfigValue != serverID)
						{
							serverID = serverIDConfigValue;
						}
					}
					workspaceDTO.ServerID = serverID.Value;

					kCura.Relativity.Client.ProcessOperationResult result = new kCura.Relativity.Client.ProcessOperationResult();
					try
					{
						//Create the workspace
						result = proxy.Repositories.Workspace.CreateAsync(templateArtifactID, workspaceDTO);

						if (result.Success)
						{
							//Manually check the results and return the workspace ID synchronously
							kCura.Relativity.Client.ProcessInformation info = proxy.GetProcessState(proxy.APIOptions, result.ProcessID);

							int iteration = 0;

							while (info.State != ProcessStateValue.Completed)
							{
								//Workspace creation takes some time  so threa.sleep ensures we wait until the workspaces is created and then get the artifact id of the new workspace
								System.Threading.Thread.Sleep(10000);
								info = proxy.GetProcessState(proxy.APIOptions, result.ProcessID);

								if (iteration > 6)
								{
									Console.WriteLine("Workspace creation timed out");
								}
								iteration++;
							}

							workspaceID = (int)info.OperationArtifactIDs.FirstOrDefault();

							Console.WriteLine("Workspace Created with Artiafact ID :" + workspaceID);

							return workspaceID;
						}
						else
						{
							throw new System.Exception(String.Format("workspace creation failed: {0}", result.Message));
						}
					}
					catch (Exception ex)
					{
						throw new System.Exception(String.Format("Unhandled Exception : {0}", ex));
					}
				}
				else
				{
					return workspaceID;
				}
			}
			catch (Exception ex)
			{
				throw new System.Exception("Create Workspace failed", ex);
			}
		}
		public void ConvertWithIndexEndTest()
		{
			var config = new CsvConfiguration { HasHeaderRecord = false };
			var rowMock = new Mock<ICsvReaderRow>();
			var headers = new[] { "Id", "Name", "Prop1", "Prop2", "Prop3" };
			var currentRecord = new[] { "1", "One", "1", "2", "3" };
			rowMock.Setup( m => m.Configuration ).Returns( config );
			rowMock.Setup( m => m.FieldHeaders ).Returns( headers );
			rowMock.Setup( m => m.CurrentRecord ).Returns( currentRecord );
			rowMock.Setup( m => m.GetField( It.IsAny<Type>(), It.IsAny<int>() ) ).Returns<Type, int>( ( type, index ) => Convert.ToInt32( currentRecord[index] ) );
			var data = new CsvPropertyMapData( typeof( Test ).GetProperty( "Dictionary" ) )
			{
				Index = 2,
				IndexEnd = 3
			};
			data.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture;

			var converter = new IDictionaryGenericConverter();
			var dictionary = (IDictionary)converter.ConvertFromString( "1", rowMock.Object, data );

			Assert.AreEqual( 2, dictionary.Count );
			Assert.AreEqual( 1, dictionary["Prop1"] );
			Assert.AreEqual( 2, dictionary["Prop2"] );
		}
        public void BindData(bool bReset)
        {
            if (Function.IsEmpty(strSysIniFile) || Function.IsEmpty(strUserIniFile))
            {
                return;
            }
            int    itemCount;
            string strValueTemp;
            string strDefValue;
            int    pos;

            string[]  valueTemp;        //配置值的集合
            string[]  valueList;        //最大、最小或下拉选项
            ConfigMsg configMsg;        //TreeList第一层节点
            ConfigMsg configMsgItem;    //TreeList第二层节点

            configMsgs.Clear();

            foreach (string nodeName in nodeNames)
            {
                configMsg             = new ConfigMsg();
                configMsg.ConfigName  = nodeName;
                configMsg.ConfigDesc  = Function.ProfileString(strSysIniFile, nodeName, "desc", "");
                configMsg.ConfigValue = Function.ProfileString(strSysIniFile, nodeName, "count", "");
                configMsg.ConfigType  = "G";            //把类型设置为“G”

                try
                {
                    itemCount = int.Parse(configMsg.ConfigValue.ToString());
                }
                catch { itemCount = 0; }
                configMsg.ConfigValue = itemCount.ToString() + "项";

                //添加配置项
                for (int j = 1; j <= itemCount; j++)
                {
                    strDefValue  = "";
                    strValueTemp = Function.ProfileString(strSysIniFile, nodeName, j.ToString(), "");
                    valueTemp    = strValueTemp.Split(new char[] { ',' });
                    if (valueTemp.Length < 2)
                    {
                        continue;
                    }

                    configMsgItem            = new ConfigMsg();
                    configMsgItem.ConfigDesc = valueTemp[0];
                    configMsgItem.ConfigName = valueTemp[0];

                    pos = valueTemp[1].IndexOf('(');
                    if (pos > 0)
                    {
                        configMsgItem.ConfigType = valueTemp[1].Substring(0, pos);
                        strDefValue = valueTemp[1].Substring(pos + 1, valueTemp[1].Length - 3);
                    }
                    else
                    {
                        configMsgItem.ConfigType = valueTemp[1];    //配置值类型
                    }

                    if (!bReset && Function.ProfileString(strUserIniFile, nodeName, configMsgItem.ConfigName, "") != "")
                    {
                        configMsgItem.ConfigValue = Function.ProfileString(strUserIniFile, nodeName, configMsgItem.ConfigName, "");
                    }
                    else
                    {
                        configMsgItem.ConfigValue = strDefValue;
                    }
                    //新标注
                    //处理Type为N(数字最大值、最小值)、L(下拉项)的项
                    if (valueTemp.Length > 2 && (configMsgItem.ConfigType == "N" || configMsgItem.ConfigType == "L" || configMsgItem.ConfigType == "C"))
                    {
                        valueList = new string[valueTemp.Length - 2];
                        for (int k = 0; k < valueList.Length; k++)
                        {
                            valueList[k] = valueTemp[2 + k];
                        }
                        configMsgItem.ConfigValueList = valueList;
                    }

                    if (configMsgItem.ConfigType == "R")
                    {
                        try
                        {
                            configMsgItem.ConfigValue = Convert.ToBoolean(configMsgItem.ConfigValue);
                        }
                        catch { configMsgItem.ConfigValue = false; }
                    }

                    if (configMsgItem.ConfigType == "C")
                    {
                        configMsgItem.ConfigValue = (configMsgItem.ConfigValue as string).Replace(";", ",");
                    }

                    configMsg.ConfigMsgs.Add(configMsgItem);
                }

                configMsgs.Add(configMsg);
            }
            this.treeList1.Nodes.Clear();
            if (configMsgs.Count == 1)
            {
                this.treeList1.DataSource = configMsgs[0].ConfigMsgs;
            }
            else
            {
                this.treeList1.DataSource = configMsgs;
            }
            this.treeList1.RefreshDataSource();
        }
Exemple #26
0
 RotationalStiffness(decimal newtonmetersperradian) : this(Convert.ToDouble(newtonmetersperradian), BaseUnit)
 {
 }
Exemple #27
0
        private void button1_Click(object sender, EventArgs e)
        {


            
            string time = DateTime.Now.ToString("yyyy-MM-dd");
           
            
            string s = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
            MessageBox.Show(s);
            string sex="0" ;
            string height="0";
            cnn.Open();
            string weight =" 0";
            string cmdText = @"SELECT sex 
                   FROM myfitsecret.sportsman 
                   WHERE userid=@userid;
                   SELECT daily_burned
                   FROM myfitsecret.calorie_tracker 
                   WHERE sportsman_id=@sportsman_id";
            using (MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
            {
                // Add both parameters to the same command
                cmd.Parameters.Add("@userid", MySqlDbType.String).Value = Login.userID;
                cmd.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID;
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    // get sum from the first result
                    if (reader.Read()) sex = ((reader[0]).ToString());

                    // if there is a second resultset, go there
                    if (reader.NextResult())
                        if (reader.Read() && !(reader[0] is DBNull))
                            Sportsman.burned += Convert.ToInt32(reader[0]);

                }
                cmd.Connection.Close();

               

                 cmdText = @"SELECT sportsman.height
                   FROM myfitsecret.sportsman 
                   WHERE userid=@userid;
                   SELECT body_progress.last_weight
                   FROM myfitsecret.body_progress 
                   WHERE sportsmanID=@sportsmanID";

                using (MySqlCommand cmd2 = new MySqlCommand(cmdText, cnn))
                {
                    cmd2.Connection.Open();

                    // Add both parameters to the same command
                    cmd2.Parameters.Add("@userid", MySqlDbType.String).Value = Login.userID;
                    cmd2.Parameters.Add("@sportsmanID", MySqlDbType.String).Value = Login.userID;
                    
                    using (MySqlDataReader reader2 = cmd2.ExecuteReader())
                    {
                        // get sum from the first result
                        if (reader2.Read()) height = (reader2[0]).ToString();

                        // if there is a second resultset, go there
                        if (reader2.NextResult())
                            if (reader2.Read())
                                weight = (reader2[0]).ToString();

                    }
                    cmd2.Connection.Close();
                    if (Sportsman.count1 == 0)
                    {
                            if (sex.Equals("male") && s.Equals("weightTraining"))
                            {
                                Sportsman.burned1 += 700 + (15 * int.Parse(weight)) + (5 * int.Parse(height)) - (7 * 30) + (int.Parse(textBox1.Text) * 14);
                                MessageBox.Show("Burned calories are updated");
                            }
                            else if (sex.Equals("male") && s.Equals("cardio"))
                            {
                                Sportsman.burned1 += 700 + (15 * int.Parse(weight)) + (5 * int.Parse(height)) - (7 * 30) + (int.Parse(textBox1.Text) * 10);
                                MessageBox.Show("Burned calories are updated");
                            }
                            else if (sex.Equals("female") && s.Equals("weightTraining"))
                            {
                                Sportsman.burned1 += 900 + (9 * int.Parse(weight)) + (2 * int.Parse(height)) - (5 * 30) + (int.Parse(textBox1.Text) * 10);
                                MessageBox.Show("Burned calories are updated");
                            }
                            else
                            {
                                Sportsman.burned1 += 900 + (9 * int.Parse(weight)) + (2 * int.Parse(height)) - (5 * 30) + (int.Parse(textBox1.Text) * 6);
                                MessageBox.Show("Burned calories are updated");
                            }
                   
                            MySqlCommand cmd5 = new MySqlCommand("UPDATE myfitsecret.calorie_tracker set daily_burned=@daily_burned where sportsman_id=@sportsman_id and Date=@Date", cnn);
                            cmd5.CommandType = CommandType.Text;
                            cmd5.Connection.Open();

                            cmd5.Parameters.AddWithValue("@daily_burned", Sportsman.burned1);
                            cmd5.Parameters.AddWithValue("@Date", time);
                            cmd5.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID;
                            cmd5.ExecuteNonQuery();
                            cmd5.Connection.Close();
                            Sportsman.count1++;

                    }
                    else {
                        if (sex.Equals("male"))
                            Sportsman.burned1 += (int.Parse(textBox1.Text) * 10);

                        else
                            Sportsman.burned1 += (int.Parse(textBox1.Text) * 6);

                        MySqlCommand cmd3 = new MySqlCommand("update myfitsecret.calorie_tracker set daily_burned=@daily_burned where sportsman_id=@sportsman_id and Date=@Date", cnn);
                        cmd3.CommandType = CommandType.Text;
                        cmd3.Connection.Open();

                        cmd3.Parameters.AddWithValue("@daily_burned", Sportsman.burned1);
                        cmd3.Parameters.AddWithValue("@Date", time);
                        cmd3.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID;
                        cmd3.ExecuteNonQuery();
                        
                    }
                    DataTable tablo = new DataTable();

                    string showTable = "SELECT daily_gained,daily_burned,Date from myfitsecret.calorie_tracker where sportsman_id=@sportsman_id";
                    MySqlDataAdapter adapter = new MySqlDataAdapter();
                    MySqlCommand showCommand = new MySqlCommand();

                    showCommand.Connection = cnn;
                    showCommand.CommandText = showTable;
                    showCommand.CommandType = CommandType.Text;
                    showCommand.Parameters.AddWithValue("@sportsman_id", Login.userID);
                    adapter.SelectCommand = showCommand;
                    adapter.Fill(tablo);

                    dataGridView1.DataSource = tablo;
                    cmd.Connection.Close();
                    cnn.Close();
                }
            }
        }
Exemple #28
0
 public RotationalStiffness(double newtonmetersperradian)
 {
     _value = Convert.ToDouble(newtonmetersperradian);
     _unit  = BaseUnit;
 }
Exemple #29
0
        public static void AppendNodeFlags(INetworkFeatureClass network, GraphTable gt, List <int> nodeIds, NetworkTracerOutputCollection output /*, IProgressReporterEvent reportEvent, ProgressReport report*/)
        {
            try
            {
                Dictionary <int, string> fcNames = new Dictionary <int, string>();
                //int counter = 0;
                //if (report != null)
                //{
                //    report.Message = "Add Nodes...";
                //    report.featurePos = 0;
                //    report.featureMax = nodeIds.Count;
                //    reportEvent.reportProgress(report);
                //}
                foreach (int nodeId in nodeIds)
                {
                    int fcId = gt.GetNodeFcid(nodeId);
                    if (fcId >= 0)
                    {
                        IFeature nodeFeature = network.GetNodeFeature(nodeId);
                        if (nodeFeature != null && nodeFeature.Shape is IPoint)
                        {
                            if (!fcNames.ContainsKey(fcId))
                            {
                                fcNames.Add(fcId, network.NetworkClassName(fcId));
                            }

                            string fcName = fcNames[fcId];

                            output.Add(new NetworkFlagOutput(nodeFeature.Shape as IPoint,
                                                             new NetworkFlagOutput.NodeFeatureData(nodeId, fcId, Convert.ToInt32(nodeFeature["OID"]), fcName)));
                        }
                    }
                    //counter++;
                    //if (report != null && counter % 1000 == 0)
                    //{
                    //    report.featurePos = counter;
                    //    reportEvent.reportProgress(report);
                    //}
                }
            }
            catch { }
        }
Exemple #30
0
        public static object GetPropertyValueByName(object src, string propName)
        {
            var propertyInfo = src.GetType().GetProperty(propName);

            return(propertyInfo != null?Convert.ToString(propertyInfo.GetValue(src, null)) : null);
        }
Exemple #31
0
        static void Main(string[] args)
        {
            /*int[] numberArray = new int[5];
            numberArray[0] = 13;
            numberArray[1] = 22;
            numberArray[2] = 3;
            numberArray[3] = 93;
            numberArray[4] = 1;

            Console.WriteLine("Check if you pickd a lucky number");
            string number = Console.ReadLine();
            int myNumber = Convert.ToInt32(number);

            for (int i = 0; i<numberArray.Length; i++)
            {
                if (myNumber == numberArray[i])
                {
                    Console.WriteLine("Winner winner chicken dinner!");
                }
                else
                {
                    Console.WriteLine("Sorry, not this time");
                }
            }

            Console.WriteLine(numberArray.Contains(myNumber));
            if (true)
            {
                Console.WriteLine("Congrats man!");
            }else
            {
                Console.WriteLine("Sorry, not this time");
            }*/

            //ÖVNING 2
            //ett sätt
            int[] firstOne = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            int[] secondOne = new int[10] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

            Console.WriteLine(string.Join(',', firstOne));
            Console.WriteLine(string.Join(',', secondOne));

            //alternativt sätt 

            Console.WriteLine(string.Join(',' ,firstOne));
            //Console.WriteLine(string.Join(',', firstOne.Reverse)); //KOLLA DENNA SEN
            string[] monthArray = new string
            {"Januari",
             "februari", 
             "mars", 
             "april",
             "maj",
             "juni", 
             "juli", 
             "augusti", 
             "september",
             "oktober", 
             "november",
             "december" 
            };

            string number;
            int choiche;

            do
            {
                Console.WriteLine("Select a number from 1-12");
                string choice = Console.ReadLine();
                int choiceInInt = Convert.ToInt32(choice);
            } while (true);



        }
Exemple #32
0
		private void ConvertClick(object sender, RoutedEventArgs e)
		{
			if (m_ghostscript.GetStatus() != gsStatus.GS_READY)
			{
				ShowMessage(NotifyType_t.MESS_STATUS, "GS busy");
				return;
			}

			if (m_convertwin == null || !m_convertwin.IsActive)
			{
				m_convertwin = new Convert(m_num_pages);
				m_convertwin.ConvertUpdateMain += new Convert.ConvertCallBackMain(ConvertReturn);
				m_convertwin.Activate();
				m_convertwin.Show();
			}
		}
        public override void Execute()
        {
            
            #line 2 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
  
    ViewBag.Title = "Create Comment Type";
    Layout = null;

            
            #line default
            #line hidden
WriteLiteral("\r\n<script>\r\n    $(document).ready(function () {\r\n        try {\r\n            var h" +
"ostingEntityName = \"\";\r\n            if (\'");

            
            #line 10 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
            Write(Convert.ToString(ViewData["AssociatedType"]));

            
            #line default
            #line hidden
WriteLiteral("\' != null) {\r\n                hostingEntityName = \'");

            
            #line 11 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                Write(Convert.ToString(ViewData["AssociatedType"]));

            
            #line default
            #line hidden
WriteLiteral("\';\r\n                 $(\'#\' + hostingEntityName + \'ID\').attr(\"lock\",\"true\");\r\n\t\t\t\t" +
"  $(\'#\' + hostingEntityName + \'ID\').trigger(\"change\");\r\n            }\r\n\t\t\t\r\n    " +
"    }\r\n        catch (ex) { }\r\n\t\t\r\n\t\t \r\n    });\r\n</script>\r\n<script");

WriteLiteral(" type=\"text/javascript\"");

WriteLiteral(@">
    var config = {
        '.chosen-select': {},
        '.chosen-select-deselect': { allow_single_deselect: true },
        '.chosen-select-no-single': { disable_search_threshold: 10 },
        '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
        '.chosen-select-width': { width: ""95%"" }
    }
    for (var selector in config) {
        $(selector).chosen(config[selector]);
    }
</script>
");

            
            #line 34 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
  
    if (!string.IsNullOrEmpty(ViewBag.T_CommenttypeIsHiddenRule))
    {
        
            
            #line default
            #line hidden
            
            #line 37 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
   Write(Html.Raw(ViewBag.T_CommenttypeIsHiddenRule));

            
            #line default
            #line hidden
            
            #line 37 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                    ;
    }

            
            #line default
            #line hidden
WriteLiteral("\r\n");

            
            #line 40 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
  
    if (!string.IsNullOrEmpty(ViewBag.T_CommenttypeIsGroupsHiddenRule))
    {
        
            
            #line default
            #line hidden
            
            #line 43 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
   Write(Html.Raw(ViewBag.T_CommenttypeIsGroupsHiddenRule));

            
            #line default
            #line hidden
            
            #line 43 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                          ;
    }

            
            #line default
            #line hidden
WriteLiteral("\r\n");

            
            #line 46 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
  
    if (!string.IsNullOrEmpty(ViewBag.T_CommenttypeIsSetValueUIRule))
    {
        
            
            #line default
            #line hidden
            
            #line 49 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
   Write(Html.Raw(ViewBag.T_CommenttypeIsSetValueUIRule));

            
            #line default
            #line hidden
            
            #line 49 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                        ;
    }

            
            #line default
            #line hidden
WriteLiteral("\r\n<link");

WriteAttribute("href", Tuple.Create(" href=\"", 1519), Tuple.Create("\"", 1568)
, Tuple.Create(Tuple.Create("", 1526), Tuple.Create<System.Object, System.Int32>(Href("~/Content/bootstrap-datetimepicker.min.css")
, 1526), false)
);

WriteLiteral(" rel=\"stylesheet\"");

WriteLiteral(" />\r\n<link");

WriteAttribute("href", Tuple.Create(" href=\"", 1596), Tuple.Create("\"", 1639)
            
            #line 53 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
, Tuple.Create(Tuple.Create("", 1603), Tuple.Create<System.Object, System.Int32>(Url.Content("~/Content/chosen.css")
            
            #line default
            #line hidden
, 1603), false)
);

WriteLiteral(" rel=\"stylesheet\"");

WriteLiteral(" type=\"text/css\"");

WriteLiteral(" />\r\n");

            
            #line 54 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
 using (Html.BeginForm("CreateQuick", "T_Commenttype",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    
            
            #line default
            #line hidden
            
            #line 56 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
Write(Html.AntiForgeryToken());

            
            #line default
            #line hidden
            
            #line 56 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                            ;
    Html.ValidationSummary(true);
    Html.EnableClientValidation();

            
            #line default
            #line hidden
WriteLiteral("\t<input");

WriteLiteral(" type=\"hidden\"");

WriteLiteral(" id=\"ErrMsgQuickAdd\"");

WriteLiteral(" />\r\n");

            
            #line 60 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
	
            
            #line default
            #line hidden
            
            #line 60 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                            

            
            #line default
            #line hidden
WriteLiteral("    <div");

WriteLiteral(" id=\"errorContainerQuickAdd\"");

WriteLiteral(" style=\"display: none\"");

WriteLiteral(">\r\n        <div");

WriteLiteral(" id=\"errorsMsgQuickAdd\"");

WriteLiteral("></div>\r\n        <div");

WriteLiteral(" id=\"errorsQuickAdd\"");

WriteLiteral("></div>\r\n    </div>\r\n");

WriteLiteral("\t<div");

WriteLiteral(" id=\"divDisplayThresholdLimit\"");

WriteLiteral(" style=\"display:none;\"");

WriteLiteral(">\r\n\t</div>\r\n");

WriteLiteral("\t <div");

WriteLiteral(" id=\"divDisplayBRmsgMandatory\"");

WriteLiteral(" style=\"display:none;\"");

WriteLiteral(">\r\n\t</div>\r\n");

WriteLiteral("\t<div");

WriteLiteral(" id=\"divDisplayBRmsgBeforeSaveProp\"");

WriteLiteral(" style=\"display:none;\"");

WriteLiteral(">\r\n\t</div>\r\n");

WriteLiteral("\t\t    <div");

WriteLiteral(" class=\"row\"");

WriteLiteral(">\r\n");

WriteLiteral("\t");

            
            #line 72 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
Write(Html.Hidden("AssociatedEntity", Convert.ToString(ViewData["AssociatedType"])));

            
            #line default
            #line hidden
WriteLiteral("\r\n");

WriteLiteral("\t");

            
            #line 73 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
Write(Html.Hidden("HostingEntityName", Convert.ToString(ViewData["HostingEntityName"])));

            
            #line default
            #line hidden
WriteLiteral("\r\n");

WriteLiteral("    ");

            
            #line 74 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
Write(Html.Hidden("HostingEntityID", Convert.ToString(ViewData["HostingEntityID"])));

            
            #line default
            #line hidden
WriteLiteral("\r\n        <div");

WriteLiteral(" class=\"col-md-12 col-sm-12 col-xs-12\"");

WriteLiteral(">\r\n            <div");

WriteLiteral(" class=\"panel panel-default AppForm\"");

WriteLiteral(">\r\n                <div");

WriteLiteral(" class=\"panel-body\"");

WriteLiteral(">\r\n               \t\t\t\t\t<div");

WriteLiteral(" class=\"row\"");

WriteLiteral(">\r\n\t\t\t\t        \r\n");

            
            #line 80 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
								
            
            #line default
            #line hidden
            
            #line 80 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                 if(User.CanView("T_Commenttype","T_Name"))
						{

            
            #line default
            #line hidden
WriteLiteral("\t\t\t\t<div");

WriteLiteral(" class=\'col-sm-6\'");

WriteLiteral(" id=\"dvT_Name\"");

WriteLiteral(">\r\n                                <div");

WriteLiteral(" class=\'form-group\'");

WriteLiteral(" title=\"\"");

WriteLiteral(">\r\n                                    <label>");

            
            #line 84 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                      Write(Html.LabelFor(model => model.T_Name));

            
            #line default
            #line hidden
WriteLiteral(" <span");

WriteLiteral(" class=\"text-danger-reg\"");

WriteLiteral(">*</span></label>\r\n\t\t\t\t\t\t\t\t\t \r\n");

WriteLiteral("                                    ");

            
            #line 86 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                               Write(Html.TextBoxFor(model => model.T_Name, new { @class = "form-control" }));

            
            #line default
            #line hidden
WriteLiteral("\r\n");

WriteLiteral("                                    ");

            
            #line 87 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                               Write(Html.ValidationMessageFor(model => model.T_Name));

            
            #line default
            #line hidden
WriteLiteral("\r\n\t\t\t\t\t\t\t\t\t\r\n                                </div>\r\n\t\t\t\t\t</div>\r\n");

            
            #line 91 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
						}

            
            #line default
            #line hidden
WriteLiteral("     \r\n\t\t\t\t\r\n");

            
            #line 94 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
					
            
            #line default
            #line hidden
            
            #line 94 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                     if(User.CanView("T_Commenttype","T_Description"))
						{

            
            #line default
            #line hidden
WriteLiteral("\t\t\t\t\t\t\t<div");

WriteLiteral(" class=\'col-sm-6\'");

WriteLiteral(" id=\"dvT_Description\"");

WriteLiteral(">\r\n                                <div");

WriteLiteral(" class=\'form-group\'");

WriteLiteral(" title=\"\"");

WriteLiteral(">\r\n                                    <label>");

            
            #line 98 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                      Write(Html.LabelFor(model => model.T_Description));

            
            #line default
            #line hidden
WriteLiteral(" </label>\r\n");

WriteLiteral("                                    ");

            
            #line 99 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                               Write(Html.TextAreaFor(model => model.T_Description, new { @class = "form-control" }));

            
            #line default
            #line hidden
WriteLiteral("\r\n");

WriteLiteral("                                    ");

            
            #line 100 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                               Write(Html.ValidationMessageFor(model => model.T_Description));

            
            #line default
            #line hidden
WriteLiteral("\r\n                                </div>\r\n\t\t\t\t\t\t\t</div>\r\n");

            
            #line 103 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
							}

            
            #line default
            #line hidden
WriteLiteral("       </div>\r\n                        </div>\r\n                    </div>\r\n      " +
"          </div>\r\n        </div>\r\n");

WriteLiteral("\t\t<button");

WriteLiteral(" id=\"CancelQuickAdd\"");

WriteLiteral(" type=\"button\"");

WriteLiteral(" class=\"btn btn-default btn-sm\"");

WriteLiteral(" data-dismiss=\"modal\"");

WriteLiteral(" aria-hidden=\"true\"");

WriteLiteral(">Cancel</button>\r\n");

            
            #line 110 "..\..\Views\T_Commenttype\CreateQuick.cshtml"

		var busineesrule = User.businessrules.Where(p => p.EntityName == "T_Commenttype").ToList();
		 var lstinlineentityname = "";
		 var lstinlineassocdispname ="";
		 var lstinlineassocname = "";
        if (ViewBag.IsAddPop != null)
		{

            
            #line default
            #line hidden
WriteLiteral("\t\t\t<input");

WriteLiteral(" type=\"submit\"");

WriteLiteral(" value=\"Create\"");

WriteLiteral(" class=\"btn btn-primary btn-sm\"");

WriteAttribute("onclick", Tuple.Create(" onclick=\"", 4646), Tuple.Create("\"", 4829)
, Tuple.Create(Tuple.Create("", 4656), Tuple.Create("QuickAdd(event,\'T_Commenttype\',\'", 4656), true)
            
            #line 117 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                        , Tuple.Create(Tuple.Create("", 4688), Tuple.Create<System.Object, System.Int32>(busineesrule
            
            #line default
            #line hidden
, 4688), false)
, Tuple.Create(Tuple.Create("", 4701), Tuple.Create("\',", 4701), true)
            
            #line 117 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                       , Tuple.Create(Tuple.Create("", 4703), Tuple.Create<System.Object, System.Int32>(busineesrule.Count
            
            #line default
            #line hidden
, 4703), false)
, Tuple.Create(Tuple.Create("", 4722), Tuple.Create(",\'OnCreate\',\'ErrMsgQuickAdd\',false,\'", 4722), true)
            
            #line 117 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                              , Tuple.Create(Tuple.Create("", 4758), Tuple.Create<System.Object, System.Int32>(lstinlineassocname
            
            #line default
            #line hidden
, 4758), false)
, Tuple.Create(Tuple.Create("", 4777), Tuple.Create("\',\'", 4777), true)
            
            #line 117 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                    , Tuple.Create(Tuple.Create("", 4780), Tuple.Create<System.Object, System.Int32>(lstinlineassocdispname
            
            #line default
            #line hidden
, 4780), false)
, Tuple.Create(Tuple.Create("", 4803), Tuple.Create("\',\'", 4803), true)
            
            #line 117 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                              , Tuple.Create(Tuple.Create("", 4806), Tuple.Create<System.Object, System.Int32>(lstinlineentityname
            
            #line default
            #line hidden
, 4806), false)
, Tuple.Create(Tuple.Create("", 4826), Tuple.Create("\');", 4826), true)
);

WriteLiteral(" />\r\n");

WriteLiteral(" <input");

WriteLiteral(" type=\"submit\"");

WriteLiteral("  value=\"Create & Continue\"");

WriteLiteral(" btnval=\"createcontinue\"");

WriteLiteral(" class=\"btn btn-primary btn-sm\"");

WriteAttribute("onclick", Tuple.Create(" onclick=\"", 4938), Tuple.Create("\"", 5121)
, Tuple.Create(Tuple.Create("", 4948), Tuple.Create("QuickAdd(event,\'T_Commenttype\',\'", 4948), true)
            
            #line 118 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                 , Tuple.Create(Tuple.Create("", 4980), Tuple.Create<System.Object, System.Int32>(busineesrule
            
            #line default
            #line hidden
, 4980), false)
, Tuple.Create(Tuple.Create("", 4993), Tuple.Create("\',", 4993), true)
            
            #line 118 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                , Tuple.Create(Tuple.Create("", 4995), Tuple.Create<System.Object, System.Int32>(busineesrule.Count
            
            #line default
            #line hidden
, 4995), false)
, Tuple.Create(Tuple.Create("", 5014), Tuple.Create(",\'OnCreate\',\'ErrMsgQuickAdd\',false,\'", 5014), true)
            
            #line 118 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                       , Tuple.Create(Tuple.Create("", 5050), Tuple.Create<System.Object, System.Int32>(lstinlineassocname
            
            #line default
            #line hidden
, 5050), false)
, Tuple.Create(Tuple.Create("", 5069), Tuple.Create("\',\'", 5069), true)
            
            #line 118 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                             , Tuple.Create(Tuple.Create("", 5072), Tuple.Create<System.Object, System.Int32>(lstinlineassocdispname
            
            #line default
            #line hidden
, 5072), false)
, Tuple.Create(Tuple.Create("", 5095), Tuple.Create("\',\'", 5095), true)
            
            #line 118 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                                                       , Tuple.Create(Tuple.Create("", 5098), Tuple.Create<System.Object, System.Int32>(lstinlineentityname
            
            #line default
            #line hidden
, 5098), false)
, Tuple.Create(Tuple.Create("", 5118), Tuple.Create("\');", 5118), true)
);

WriteLiteral(" />\r\n");

            
            #line 119 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
		}
		else
		{

            
            #line default
            #line hidden
WriteLiteral("\t\t\t<input");

WriteLiteral(" type=\"submit\"");

WriteLiteral(" value=\"Create\"");

WriteLiteral(" class=\"btn btn-primary btn-sm\"");

WriteAttribute("onclick", Tuple.Create(" onclick=\"", 5214), Tuple.Create("\"", 5441)
, Tuple.Create(Tuple.Create("", 5224), Tuple.Create("QuickAddFromIndex(event,true,\'T_Commenttype\',\'", 5224), true)
            
            #line 122 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                      , Tuple.Create(Tuple.Create("", 5270), Tuple.Create<System.Object, System.Int32>(ViewData["AssociatedType"]
            
            #line default
            #line hidden
, 5270), false)
, Tuple.Create(Tuple.Create("", 5297), Tuple.Create("\',\'", 5297), true)
            
            #line 122 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                    , Tuple.Create(Tuple.Create("", 5300), Tuple.Create<System.Object, System.Int32>(busineesrule
            
            #line default
            #line hidden
, 5300), false)
, Tuple.Create(Tuple.Create("", 5313), Tuple.Create("\',", 5313), true)
            
            #line 122 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                   , Tuple.Create(Tuple.Create("", 5315), Tuple.Create<System.Object, System.Int32>(busineesrule.Count
            
            #line default
            #line hidden
, 5315), false)
, Tuple.Create(Tuple.Create("", 5334), Tuple.Create(",\'OnCreate\',\'ErrMsgQuickAdd\',false,\'", 5334), true)
            
            #line 122 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                          , Tuple.Create(Tuple.Create("", 5370), Tuple.Create<System.Object, System.Int32>(lstinlineassocname
            
            #line default
            #line hidden
, 5370), false)
, Tuple.Create(Tuple.Create("", 5389), Tuple.Create("\',\'", 5389), true)
            
            #line 122 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                                                , Tuple.Create(Tuple.Create("", 5392), Tuple.Create<System.Object, System.Int32>(lstinlineassocdispname
            
            #line default
            #line hidden
, 5392), false)
, Tuple.Create(Tuple.Create("", 5415), Tuple.Create("\',\'", 5415), true)
            
            #line 122 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                                                                          , Tuple.Create(Tuple.Create("", 5418), Tuple.Create<System.Object, System.Int32>(lstinlineentityname
            
            #line default
            #line hidden
, 5418), false)
, Tuple.Create(Tuple.Create("", 5438), Tuple.Create("\');", 5438), true)
);

WriteLiteral(" />\r\n");

WriteLiteral(" <input");

WriteLiteral(" type=\"submit\"");

WriteLiteral(" value=\"Create & Continue\"");

WriteLiteral(" btnval=\"createcontinue\"");

WriteLiteral(" class=\"btn btn-primary btn-sm\"");

WriteAttribute("onclick", Tuple.Create(" onclick=\"", 5549), Tuple.Create("\"", 5776)
, Tuple.Create(Tuple.Create("", 5559), Tuple.Create("QuickAddFromIndex(event,true,\'T_Commenttype\',\'", 5559), true)
            
            #line 123 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                              , Tuple.Create(Tuple.Create("", 5605), Tuple.Create<System.Object, System.Int32>(ViewData["AssociatedType"]
            
            #line default
            #line hidden
, 5605), false)
, Tuple.Create(Tuple.Create("", 5632), Tuple.Create("\',\'", 5632), true)
            
            #line 123 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                            , Tuple.Create(Tuple.Create("", 5635), Tuple.Create<System.Object, System.Int32>(busineesrule
            
            #line default
            #line hidden
, 5635), false)
, Tuple.Create(Tuple.Create("", 5648), Tuple.Create("\',", 5648), true)
            
            #line 123 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                           , Tuple.Create(Tuple.Create("", 5650), Tuple.Create<System.Object, System.Int32>(busineesrule.Count
            
            #line default
            #line hidden
, 5650), false)
, Tuple.Create(Tuple.Create("", 5669), Tuple.Create(",\'OnCreate\',\'ErrMsgQuickAdd\',false,\'", 5669), true)
            
            #line 123 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                                                  , Tuple.Create(Tuple.Create("", 5705), Tuple.Create<System.Object, System.Int32>(lstinlineassocname
            
            #line default
            #line hidden
, 5705), false)
, Tuple.Create(Tuple.Create("", 5724), Tuple.Create("\',\'", 5724), true)
            
            #line 123 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                                                                        , Tuple.Create(Tuple.Create("", 5727), Tuple.Create<System.Object, System.Int32>(lstinlineassocdispname
            
            #line default
            #line hidden
, 5727), false)
, Tuple.Create(Tuple.Create("", 5750), Tuple.Create("\',\'", 5750), true)
            
            #line 123 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
                                                                                                                                                                                                                                  , Tuple.Create(Tuple.Create("", 5753), Tuple.Create<System.Object, System.Int32>(lstinlineentityname
            
            #line default
            #line hidden
, 5753), false)
, Tuple.Create(Tuple.Create("", 5773), Tuple.Create("\');", 5773), true)
);

WriteLiteral(" />\r\n");

            
            #line 124 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
		}
}

            
            #line default
            #line hidden
WriteLiteral("<script");

WriteAttribute("src", Tuple.Create(" src=\"", 5797), Tuple.Create("\"", 5838)
            
            #line 126 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
, Tuple.Create(Tuple.Create("", 5803), Tuple.Create<System.Object, System.Int32>(Url.Content("~/bundles/jqueryval")
            
            #line default
            #line hidden
, 5803), false)
);

WriteLiteral(" type=\"text/javascript\"");

WriteLiteral("></script>\r\n<script");

WriteAttribute("src", Tuple.Create(" src=\"", 5881), Tuple.Create("\"", 5920)
            
            #line 127 "..\..\Views\T_Commenttype\CreateQuick.cshtml"
, Tuple.Create(Tuple.Create("", 5887), Tuple.Create<System.Object, System.Int32>(Url.Content("~/bundles/common3")
            
            #line default
            #line hidden
, 5887), false)
);

WriteLiteral(" type=\"text/javascript\"");

WriteLiteral("></script>\r\n\r\n\r\n<script");

WriteLiteral(" type=\'text/javascript\'");

WriteLiteral(@">
    $(document).ready(function () {
        try {
            document.getElementsByTagName(""body"")[0].focus();
            $(""#addPopup"").removeAttr(""tabindex"");
            var cltcoll = $(""#dvPopup"").find('input[type=text]:not([class=hidden]):not([readonly]),textarea:not([readonly])');
            var cltid = """";
            $(cltcoll).each(function () {
			  if ($(this).attr(""id"") == undefined)
                    return
                var dvhidden = $(""#dv"" + $(this).attr(""id""));
				var dvDate = $(""#datetimepicker"" + $(this).attr(""id"")).attr(""id"");

                if (!(dvhidden.css('display') == 'none') && dvDate == undefined) {
                    cltid = $(this);
                    return false;
                }
            });
            if (cltid != """" && cltid != undefined)
                setTimeout(function () { $(cltid).focus(); }, 500);
			var ctrlReadonly = $(""#dvPopup"").find('input[type=text][readonly],textarea[readonly]');
            $(ctrlReadonly).each(function () {
                $(ctrlReadonly).attr(""tabindex"", ""-1"");
            });
        }
        catch (ex) { }
    });
</script>

");

        }
Exemple #34
0
 public void Setup()
 {
     converter=new Convert();
 }
Exemple #35
0
        //合同归档
        private void button1_Click(object sender, EventArgs e)
        {
            if (IsMoney(this.textBox1.Text) && IsMoney(this.textBox2.Text))
            {
                MessageBox.Show("ok");
                DialogResult dr = openFileDialog1.ShowDialog();
                //获取所打开文件的文件名
                string openfilename = openFileDialog1.FileName;

                if (dr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(openfilename))
                {
                    string pLocalFilePath = openfilename;//要复制的文件路径
                    string filename1      = System.IO.Path.GetFileName(pLocalFilePath);

                    string pSaveFilePath = "return/" + _name;           //指定存储的路径
                                                                        // MessageBox.Show(pSaveFilePath);
                    if (File.Exists(pLocalFilePath))                    //必须判断要复制的文件是否存在
                    {
                        File.Copy(pLocalFilePath, pSaveFilePath, true); //三个参数分别是源文件路径,存储路径,若存储路径有相同文件是否替换
                        DateTime dt = DateTime.Now;
                        contractreturned(_name, pSaveFilePath, dt.ToString(), Convert.ToDecimal(this.textBox1.Text), Convert.ToDecimal(this.textBox2.Text));

                        //showcontractdetailtable();

                        //this.button11.Enabled = true;
                        //this.button12.Enabled = false;
                        //openurl = pSaveFilePath;
                    }
                }
            }
            else
            {
                MessageBox.Show("数字输入错误");
                return;
            }
        }
Exemple #36
0
        static void RunApplication()
        {
            CoreDLL.SystemIdleTimerReset();

            //comandos.Name = "comandos";
            //comandos.Clear();
            //posicion.Name = "posicion";
            //status.Name = "status";
            mobile.StackFailure += ClientMobileStackFailure;
            mobile.destination   = new Destination();
            try
            {
                ServerAddress = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["ip_address"]) ?? IPAddress.Any, 2357);
                HostAddress   = new IPEndPoint(IPAddress.Parse("169.254.2.2") ?? IPAddress.Any, 2357);

                // establezo la direccion UDP y UIQ (inter queue)
                //mobile.destination.UIQ = mobile.destination.UDP = SystemState.ActiveSyncStatus == ActiveSyncStatus.Synchronizing ? HostAddress : ServerAddress;
                mobile.destination.UIQ = mobile.destination.UDP = ServerAddress;

                restart_timer = Convert.ToInt32(ConfigurationManager.AppSettings["restart_timer"]);
                if (restart_timer == 0)
                {
                    restart_timer = 300 * 1000;
                }
                shutdown_timer = Convert.ToInt32(ConfigurationManager.AppSettings["shutdown_timer"]);
                if (shutdown_timer == 0)
                {
                    shutdown_timer = 300 * 1000;
                }
                connection_timer = Convert.ToInt32(ConfigurationManager.AppSettings["connection_timer"]);
                if (connection_timer == 0)
                {
                    connection_timer = 60 * 1000;
                }
                GpsMinimunPDOP = Convert.ToInt32(ConfigurationManager.AppSettings["gps_min_pdop"]);
                if (GpsMinimunPDOP == 0)
                {
                    GpsMinimunPDOP = 8;
                }
                fix_interval = Convert.ToInt32(ConfigurationManager.AppSettings["gps_fix_interval"]);
                if (fix_interval == 0)
                {
                    fix_interval = 60;
                }
                destination_area_radio = Convert.ToInt32(ConfigurationManager.AppSettings["gps_area_radio"]);
                if (destination_area_radio == 0)
                {
                    destination_area_radio = 1500;
                }
                //notschedule = (ConfigurationManager.AppSettings["hack_not_re_schedule"] == "active" ? true : false);
                var auto_gc = ConfigurationManager.AppSettings["hack_auto_gc"];

                /*if (!string.IsNullOrEmpty(auto_gc)) {
                 *  T.TRACE(String.Format("HACK: Activo GeoCerca Automatica de Pruebas {0}",auto_gc));
                 *  var dummy = new byte[2];
                 *  comandos.Push(auto_gc, dummy);
                 * }*/
            }
            catch (Exception)
            {
                T.ERROR("ERROR FATAL: La configuracion no es valida, revisar.");
                T.ERROR("CUIDADO!!! No se programa el restart, debe ejecutar la aplicacion manualmente.");
                return;
            }

#if false
            mobile.IMEI = iPaqUtil.GetDeviceSN();
#else
            mobile.IMEI = "HTC-GUSTAVO";
#endif
            using (var script_hlp = File.Create(@"\Temp\pdaserial.txt"))
            {
                var buffer = Encoding.ASCII.GetBytes(mobile.IMEI);
                script_hlp.Write(buffer, 0, buffer.GetLength(0));
            }

            mobile.Password = "******";
            mobile.Init(2357, 2358, 8192, "entrante", "saliente");
            T.INFO("COMM: Init convocado.");

            network = new Thread(NetworkProc);
            T.INFO("NETWORK: lanzando hilo.");
            network.Start();

            tracker = new Thread(TrackerProc);
            T.INFO("TRACKER: lanzando hilo.");
            tracker.Start();

            CoreDLL.SystemIdleTimerReset();

            IntPtr wavHandle = CoreDLL.SetPowerRequirement("WAV1:",
                                                           CEDEVICE_POWER_STATE.D0,
                                                           DevicePowerFlags.POWER_NAME | DevicePowerFlags.POWER_FORCE, IntPtr.Zero, 0);
            if (wavHandle == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception();
            }

            var gpsHandle = CoreDLL.SetPowerRequirement("GPD0:",
                                                        CEDEVICE_POWER_STATE.D0,
                                                        DevicePowerFlags.POWER_NAME | DevicePowerFlags.POWER_FORCE, IntPtr.Zero, 0);
            if (gpsHandle == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception();
            }

            CoreDLL.Beep(1);
            T.TRACE("Lanzando Urbetrack Ready");
            LaunchGatewayRunning();

            var upgrade_count = 0;
            while (running)
            {
                CoreDLL.SystemIdleTimerReset();
                if (upgrade_count == 0)
                {
                    T.TRACE("Lanzando Urbetrack Update");
                    LaunchGatewayUpgrade();
                    upgrade_count = 360;
                }
                upgrade_count--;
                for (var x = 0; x < 10; x++)
                {
                    Thread.Sleep(1000);
                    Application.DoEvents();
                }
                var comando = "";
                try
                {
                    Thread.Sleep(1000);

                    /*comandos.Pop(ref comando);
                     * if (comando.Length > 0)
                     *  ProcessCommand(comando);*/
                } catch (Exception e)
                {
                    T.EXCEPTION(e, "Command Processor");
                }
            }

            if (wavHandle != IntPtr.Zero)
            {
                CoreDLL.ReleasePowerRequirement(wavHandle);
            }

            if (gpsHandle != IntPtr.Zero)
            {
                CoreDLL.ReleasePowerRequirement(gpsHandle);
            }

            T.INFO("URBEMOBILE: hora de ahorar energia...");
            mobile.Close();
            network.Join(10000);
            T.INFO("URBEMOBILE: network sincronizada.");
            //supervisor.Join(10000);
            //T.INFO("URBEMOBILE: supervisor sincornizado.");
            tracker.Join(10000);
            T.INFO("URBEMOBILE: tracker sincornizado.");

            T.TRACE("--- URBEMOBILE TERMINADO ---");

            Beep("end_app");
        }
Exemple #37
0
		public MainWindow()
		{
			InitializeComponent();
			this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing);
			m_file_open = false;
			m_regstartup = true;
			m_showannot = true;

			/* Allocations and set up */
			try
			{
				m_docPages = new Pages();
				m_thumbnails = new List<DocPage>();
				m_lineptrs = new List<LinesText>();
				m_textptrs = new List<BlocksText>();
				m_textset = new List<Boolean>();
				m_ghostscript = new ghostsharp();
				m_ghostscript.gsUpdateMain += new ghostsharp.gsCallBackMain(gsProgress);
				m_gsoutput = new gsOutput();
				m_gsoutput.Activate();
				m_outputintents = new OutputIntent();
				m_outputintents.Activate();
				m_ghostscript.gsIOUpdateMain += new ghostsharp.gsIOCallBackMain(gsIO);
				m_ghostscript.gsDLLProblemMain += new ghostsharp.gsDLLProblem(gsDLL);
				m_convertwin = null;
				m_extractwin = null;
				m_selection = null;
				xaml_ZoomSlider.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler(ZoomReleased), true);
				xaml_PageList.AddHandler(Grid.DragOverEvent, new System.Windows.DragEventHandler(Grid_DragOver), true);
				xaml_PageList.AddHandler(Grid.DropEvent, new System.Windows.DragEventHandler(Grid_Drop), true);
				DimSelections();
				status_t result = CleanUp();

				string[] arguments = Environment.GetCommandLineArgs();
				if (arguments.Length > 1)
				{
					string filePath = arguments[1];
					ProcessFile(filePath);
				}
				else
				{
					if (m_regstartup)
						InitFromRegistry();
				}
			}
			catch (OutOfMemoryException e)
			{
				Console.WriteLine("Memory allocation failed at initialization\n");
				ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
			}
		}
Exemple #38
0
 public Queries(IConfiguration configuration)
 {
     _configuration = configuration;
     _credentials   = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _configuration.PersonalAccessToken)));
 }
 	public ActionResult GetGrid(JqGridRequest request, string key, string value, string viewModel, string field, long? id_master)
     {
 
         string fieldMain = String.Empty;
         long ID_master;
         bool result = Int64.TryParse(id_master.ToString(), out ID_master);
 
 
         if (String.IsNullOrEmpty(field))
         {
             fieldMain = "ID_Zapis";
         }
 
         else
         {
             fieldMain = field;
         }
 
 		viewModel = gridModelNamespace + viewModel;
 
         string filterExpression = String.Empty;
         if (request.Searching)
         {
             if (request.SearchingFilter != null)
                 filterExpression = GetFilter(request.SearchingFilter.SearchingName, request.SearchingFilter.SearchingOperator, request.SearchingFilter.SearchingValue);
             else if (request.SearchingFilters != null)
             {
                 StringBuilder filterExpressionBuilder = new StringBuilder();
                 string groupingOperatorToString = request.SearchingFilters.GroupingOperator.ToString();
                 foreach (JqGridRequestSearchingFilter searchingFilter in request.SearchingFilters.Filters)
                 {
                     filterExpressionBuilder.Append(GetFilter(searchingFilter.SearchingName, searchingFilter.SearchingOperator, searchingFilter.SearchingValue));
                     filterExpressionBuilder.Append(String.Format(KeyWord.FormaterRazno.StringFormat.Prvi, groupingOperatorToString));
                 }
                 if (filterExpressionBuilder.Length > 0)
                     filterExpressionBuilder.Remove(filterExpressionBuilder.Length - groupingOperatorToString.Length - 2, groupingOperatorToString.Length + 2);
                 filterExpression = filterExpressionBuilder.ToString();
             }
 
         }
         string sortingName = request.SortingName;
         long totalRecordsCount = GetCount(filterExpression, key, value);
 
 
         JqGridResponse response = new JqGridResponse()
         {
             TotalPagesCount = (int)Math.Ceiling((float)totalRecordsCount / (float)request.RecordsCount),
             PageIndex = request.PageIndex,
             TotalRecordsCount = totalRecordsCount,
         };
 
 
         response.Records.AddRange
             (
             from item in GetGridData(filterExpression, key, value, String.Format(KeyWord.FormaterRazno.StringFormat.PrviDrugi, sortingName, request.SortingOrder), request.PageIndex * request.RecordsCount, (request.PagesCount.HasValue ? request.PagesCount.Value : 1) * request.RecordsCount)
             select new JqGridRecord(Convert.ToString(item.GetType().GetProperty(fieldMain).GetValue(item, null)), Activator.CreateInstance(Type.GetType(viewModel), new[] { item }))
             );
 
 
         return new JqGridJsonResult() { Data = response };
     }
Exemple #40
0
        static void Main(string[] args)
        {
            // Input a and b are two integers. Calculate how many integers in the range [a..b] are divided by 3 without remainder.
            Console.WriteLine("Input integer a: ");
            int a = Int32.Parse(Console.ReadLine());

            Console.WriteLine("Input integer b: ");
            int b = Int32.Parse(Console.ReadLine());
            int k = 0;

            for (int i = b; i >= a; i--)
            {
                if (i % 3 == 0)
                {
                    k = k + 1;
                }
            }

            // Input a character string. Print each second character
            Console.WriteLine($"In the range[{a}...{b}]  {k} integers are divided by 3 without remainder. ");

            Console.WriteLine("Input charecter string:");
            string text = Console.ReadLine();

            string[] words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < words.Length; i++)
            {
                if (i % 2 == 0 || i == 0)
                {
                }
                else
                {
                    Console.WriteLine(words[i]);
                }
            }

            // Input the name of the drink(coffee, tea, juice, water). Print the name of the drink and its price.
            Console.WriteLine("Input the name of drink (coffee,tea,juice,water): ");
            string drink = Console.ReadLine();

            switch (drink)
            {
            case "coffee":
            {
                Console.WriteLine($"You choose coffee. It cost 1$.");
                break;
            }

            case "tea":
            {
                Console.WriteLine($"You choose tea. It cost 0.8 $.");
                break;
            }

            case "juice":
            {
                Console.WriteLine($"You choose juice. It cost 2$.");
                break;
            }

            case "water":
            {
                Console.WriteLine($"You choose water. It cost 0.5 $.");
                break;
            }

            default:
            {
                Console.WriteLine("Sorry, we haven't this drink, good luck!");
                break;
            }
            }
            // Input a sequence of positive integers(to the first negative). Calculate the arithmetic average of the entered numbers.

            Console.WriteLine("Input a sequence of positive integers:");
            int average = 0;
            int Sum     = 0;

            for (int i = 1; i < 100; i++)
            {
                int[] digits = new int[100];
                digits[i - 1] = Convert.ToInt32(Console.ReadLine());
                if (digits[i - 1] < 0)
                {
                    break;
                }

                Sum     = Sum + digits[i - 1];
                average = Sum / i;
            }

            Console.WriteLine($"Average Sum of entered number is {average} ");

            // Check whether the entered year is a leap.
            Console.WriteLine("Input the year:");
            int year = Convert.ToInt32(Console.ReadLine());

            if (year % 4 == 0)
            {
                Console.WriteLine($" {year} is leap!");
            }
            else
            {
                Console.WriteLine($"{year} isn't leap!");
            }

            // Find the sum of digits of the entered integer number
            Console.WriteLine("Input integer number");
            int number   = Convert.ToInt32(Console.ReadLine());
            int dig      = 0;
            int sumdigit = 0;
            int odd      = 0;

            while (number > 10)
            {
                dig      = number % 10;
                number   = number / 10;
                sumdigit = sumdigit + dig;
                if (dig % 2 == 0)
                {
                    odd = odd + 1;
                }
            }

            sumdigit = sumdigit + number;

            Console.WriteLine($"Sum of digit = {sumdigit}");

            // Check whether the entered integer number contains only odd numbers

            if (odd > 0)
            {
                Console.WriteLine("Entered integer number contains NOT only odd numbers.");
            }
            else
            {
                Console.WriteLine("Entered integer number contains only odd numbers!");
            }

            Console.ReadLine();
        }
 private AccountNumber()
 {
     AccountNumber.convert = new Convert();
 }
Exemple #42
0
        /// <summary>
        /// Função para encriptação de string
        /// </summary>
        /// <param name="Exp">String a ser codificada</param>
        /// <param name="Chv">Chave para ser usada na codificação</param>
        /// <returns>Retorna a string encriptada</returns>
        public static string S001(string Exp, string Chv)
        {
            string RetVal, ExpChv, pi, pp;
            int    i, j, Cont, t, ContChv;

            string[] Dados;
            byte     bit;

            t     = Exp.Length;
            Dados = new string[t];

            ExpChv = "";

            //vamos montar a chave para encriptação
            for (i = 0; i < Chv.Length; i++)
            {
                for (j = 7; j >= 0; j--)
                {
                    bit     = Convert.ToByte((Utility.Asc(Chv.Substring(i, 1)) & (long)Math.Pow(2, j)) != 0);
                    ExpChv += Convert.ToString(bit);
                }
            }

            //vamos misturar os bits da string
            ContChv = 0;
            for (Cont = 0; Cont < t; Cont++)
            {
                pp = "";
                pi = "";
                for (j = 7; j >= 0; j--)
                {
                    // se ímpar...
                    if ((j & 1) != 0)
                    {
                        //usa o primeiro char
                        bit = Convert.ToByte(((Utility.Asc(Exp.Substring(Cont, 1)) & (long)Math.Pow(2, j)) != 0) ^
                                             (Convert.ToInt32(ExpChv.Substring(ContChv, 1)) != 0));
                        pi += Convert.ToString(bit);
                    }
                    // par
                    else
                    {
                        // usa o último char
                        bit = Convert.ToByte(((Utility.Asc(Exp.Substring(t - Cont - 1, 1)) & (long)Math.Pow(2, j)) != 0) ^
                                             (Convert.ToInt32(ExpChv.Substring(ContChv, 1)) != 0));
                        pp += Convert.ToString(bit);
                    }
                    ContChv += 1;
                    if (ContChv == ExpChv.Length)
                    {
                        ContChv = 0;
                    }
                }
                Dados[Cont] = (pp + pi);
            }

            //agora vamos montar a string já encriptada para retorno
            RetVal = "";
            for (i = 0; i < t; i++)
            {
                RetVal += Utility.Chr(RetAsc(Dados[i]));
            }

            return(RetVal);
        }
 StrStatusString = GetChangeStatusString(Convert.ToInt16(drpStatus.SelectedValue));
Exemple #44
0
        /// <summary>
        /// Função para desencriptação de string
        /// </summary>
        /// <param name="Exp">String a ser codificada</param>
        /// <param name="Chv">Chave para ser usada na codificação</param>
        /// <returns>retorna a string decriptada</returns>
        static public string S002(string Exp, string Chv)
        {
            string RetVal, z, ExpChv;

            string[] Dados;
            int      j, i, Cont, t, ContChv, k, ContIni;
            byte     bit;

            t      = Exp.Length;
            Dados  = new string[t];
            ExpChv = "";

            //vamos montar a chave para encriptação
            for (i = 0; i < Chv.Length; i++)
            {
                for (j = 7; j >= 0; j--)
                {
                    bit     = Convert.ToByte((Utility.Asc(Chv.Substring(i, 1)) & (long)Math.Pow(2, j)) != 0);
                    ExpChv += Convert.ToString(bit);
                }
            }

            //desfaz o xor com a chave  (a posição de chave que deverá ser utilizada para desencriptar cada byte deverá ser: 13570246)
            ContChv = 0;
            for (i = 0; i < Exp.Length; i++)
            {
                z        = "";
                ContIni  = ContChv;
                ContChv += 1;
                if (ContChv == ExpChv.Length)
                {
                    ContChv = 0;
                }
                for (j = 0; j <= 7; j++)
                {
                    bit = Convert.ToByte(Convert.ToInt32((Utility.Asc(Exp.Substring(i, 1)) & (long)Math.Pow(2, j)) != 0) ^
                                         Convert.ToInt32(ExpChv.Substring(ContChv, 1)));
                    z = z + Convert.ToString(bit);
                    if (j == 3)
                    {
                        ContChv = ContIni;
                    }
                    else
                    {
                        for (k = 1; k <= 2; k++)
                        {
                            ContChv += 1;
                            if (ContChv == ExpChv.Length)
                            {
                                ContChv = 0;
                            }
                        }
                    }
                }
                Utility.ChangeStr(ref Exp, i, Utility.Chr(RetAsc(z)));
            }

            //agora vamos corrigir a posição de cada bit
            for (Cont = 0; Cont < t; Cont++)
            {
                for (j = 7; j >= 0; j--)
                {
                    // se ímpar...
                    if ((j & 1) != 0)
                    {
                        // calcula bit original
                        i = (7 - Convert.ToInt32(j / 2));

                        // usa primeiro char
                        bit = Convert.ToByte(Convert.ToInt32(Utility.Asc(Exp.Substring(Cont, 1)) & (long)Math.Pow(2, i)) != 0);
                    }
                    // par
                    else
                    {
                        // calcula bit original...
                        i = 3 - (j / 2);

                        // usa último char
                        bit = Convert.ToByte(Convert.ToInt32(Utility.Asc(Exp.Substring(t - Cont - 1, 1)) & (long)Math.Pow(2, i)) != 0);
                    }
                    Dados[Cont] = Convert.ToString(bit) + Dados[Cont];
                }
            }

            //agora vamos montar a string já desencriptada para retorno
            RetVal = "";
            for (i = 0; i < t; i++)
            {
                RetVal += Utility.Chr(RetAsc(Dados[i]));
            }

            return(RetVal);
        }
        public static bool ConcelConfirm(string ID, string FromType, string OrderNo, List<ProductModel> ProductMList, List<ProductModel> ProductMStorList, out string Reason)
        {
            try
            {
                Reason = string.Empty;
                //不可以确认返回false
                if (!PurchaseOrderDBHelper.CanConcel(ID, out Reason))
                    return false;
                ArrayList lstConcelConfirm = new ArrayList();
                //更新主表
                SqlCommand ConcelPri = PurchaseOrderDBHelper.ConcelConfirm(ID);
                lstConcelConfirm.Add(ConcelPri);

                //更新分仓存量表
                if (ProductMStorList != null)
                {
                    foreach (ProductModel ProductM in ProductMStorList)
                    {
                        SqlCommand comm = PurchaseOrderDBHelper.WriteStorgeDecr(ProductM);
                        lstConcelConfirm.Add(comm);
                    }
                }
                if (ProductMList != null)
                {
                    if (FromType == "2")
                    {//回写采购计划
                        foreach (ProductModel ProductM in ProductMList)
                        {
                            SqlCommand comm = PurchaseOrderDBHelper.WritePurPlanDecr(ProductM);
                            lstConcelConfirm.Add(comm);
                        }
                    }
                    else if (FromType == "4")
                    {//回写采购合同
                        foreach (ProductModel ProductM in ProductMList)
                        {
                            SqlCommand comm = PurchaseOrderDBHelper.WritePurContDecr(ProductM);
                            lstConcelConfirm.Add(comm);
                        }
                    }
                }
                //获取登陆用户信息
                UserInfoUtil userInfo = (UserInfoUtil)SessionUtil.Session["UserInfo"];

                //撤销审批
                string CompanyCD = userInfo.CompanyCD;
                string BillTypeFlag = ConstUtil.CODING_RULE_PURCHASE;
                string BillTypeCode = ConstUtil.CODING_RULE_PURCHASE_ORDER;
                string strUserID = userInfo.UserID; ;
                DataTable dt = FlowDBHelper.GetFlowInstanceInfo(CompanyCD, Convert.ToInt32(BillTypeFlag), Convert.ToInt32(BillTypeCode), Convert.ToInt32(ID));
                if (dt.Rows.Count > 0)
                {
                    string FlowInstanceID = dt.Rows[0]["FlowInstanceID"].ToString();
                    string FlowStatus = dt.Rows[0]["FlowStatus"].ToString();
                    string FlowNo = dt.Rows[0]["FlowNo"].ToString();

                    lstConcelConfirm.Add(FlowDBHelper.CancelConfirmHis(CompanyCD, FlowInstanceID, FlowNo, BillTypeFlag, BillTypeCode, strUserID));
                    lstConcelConfirm.Add(FlowDBHelper.CancelConfirmTsk(CompanyCD, FlowInstanceID, strUserID));
                    lstConcelConfirm.Add(FlowDBHelper.CancelConfirmIns(CompanyCD, FlowNo, BillTypeFlag, BillTypeCode, ID, strUserID));
                }

                //定义返回变量
                bool isSucc = false;
                /* 
                 * 定义日志内容变量 
                 * 增删改相关的日志,需要输出操作日志,该类型日志插入到数据库
                 * 其他的 如出现异常时,需要输出系统日志,该类型日志保存到日志文件
                 */

                //执行插入操作
                try
                {
                    isSucc = SqlHelper.ExecuteTransWithArrayList(lstConcelConfirm);
                }
                catch (Exception ex)
                {
                    //输出日志
                    WriteSystemLog(userInfo, ex);
                }
                //定义变量
                string remark;
                //成功时
                if (isSucc)
                {
                    //设置操作成功标识
                    remark = ConstUtil.LOG_PROCESS_SUCCESS;
                }
                else
                {
                    //设置操作成功标识 
                    remark = ConstUtil.LOG_PROCESS_FAILED;
                }

                LogInfoModel logModel = InitLogInfo(OrderNo);
                //涉及关键元素 这个需要根据每个页面具体设置,本页面暂时设置为空
                logModel.Element = ConstUtil.LOG_PROCESS_UNCONFIRM;
                //设置操作成功标识
                logModel.Remark = remark;

                //登陆日志
                LogDBHelper.InsertLog(logModel);
                return isSucc;
            }
            catch (Exception ex)
            {
                throw ex;
            }



        }
        public static string Mod11Base7Bradesco(string seq, int b)
        {
            #region Trecho do manual layout_cobranca_port.pdf do BRADESCO

            /*
             * Para o c�lculo do d�gito, ser� necess�rio acrescentar o n�mero da carteira � esquerda antes do Nosso N�mero,
             * e aplicar o m�dulo 11, com base 7.
             * Multiplicar cada algarismo que comp�e o n�mero pelo seu respectivo multiplicador (PESO).
             * Os multiplicadores(PESOS) variam de 2 a 7.
             * O primeiro d�gito da direita para a esquerda dever� ser multiplicado por 2, o segundo por 3 e assim sucessivamente.
             *
             * Carteira   Nosso Numero
             *  ______   _________________________________________
             *  1    9   0   0   0   0   0   0   0   0   0   0   2
             *  x    x   x   x   x   x   x   x   x   x   x   x   x
             *  2    7   6   5   4   3   2   7   6   5   4   3   2
             *  =    =   =   =   =   =   =   =   =   =   =   =   =
             *  2 + 63 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 4 = 69
             *
             * O total da soma dever� ser dividido por 11: 69 / 11 = 6 tendo como resto = 3
             * A diferen�a entre o divisor e o resto, ser� o d�gito de autoconfer�ncia: 11 - 3 = 8 (d�gito de auto-confer�ncia)
             *
             * Se o resto da divis�o for �1�, desprezar o c�lculo de subtra��o e considerar o d�gito como �P�.
             * Se o resto da divis�o for �0�, desprezar o c�lculo de subtra��o e considerar o d�gito como �0�.
             */
            #endregion

            /* Vari�veis
             * -------------
             * s - Soma
             * p - Peso
             * b - Base
             * r - Resto
             */

            int s = 0, p = 2;

            for (int i = seq.Length; i > 0; i--)
            {
                s = s + (Convert.ToInt32(Mid(seq, i, 1)) * p);
                if (p == b)
                {
                    p = 2;
                }
                else
                {
                    p = p + 1;
                }
            }

            int r = (s % 11);

            if (r == 0)
            {
                return("0");
            }
            else if (r == 1)
            {
                return("P");
            }
            else
            {
                return((11 - r).ToString());
            }
        }