majormayer

majormayer 查看完整档案

重庆编辑中国人民大学  |  .NET 前端 node do 编辑重庆人人生活家  |  电视端开发 编辑 majormayer.oschina.io/nav/ 编辑
编辑
       "\
   _.  \
,-"      \
 \        \
\ \    秘   \
 \ \     籍   \  
  \ \        .-;
   \ \    _.-   :
    \ \,-"    _.-"
     \(   _.-"
      `--"

个人动态

majormayer 提出了问题 · 2020-04-28

帮忙研究下这个网页如何实现inline video 的

众所周知
在H5开发中
video标签 在 安卓手机上会出现

  1. 层级过高
  2. 浮动
  3. 无法自动播放

的问题,无论是打开 优酷 , bilbili 都没有解决这个问题

但是今天发现一个 页面 居然所有浏览器全不兼容,非常的完美
不知道怎么实现的,看了一下也没看出所以然
广大的开发者 一起来 研究下吧

这是完美解决了 h5 video 同层问题的 链接地址:

inline video

关注 1 回答 0

majormayer 收藏了文章 · 2020-04-26

超实用迷你js判断类库介绍

这个类库是干嘛的?

平时项目的开发难免遇到大量的逻辑判断,于是我将一些常用的判断封装成了一个js类库,judge.js是我用业余时间写的一个js判断类库,可以用来判断数据类型(isFunction,isObject,isJson,isArray等),判断浏览器内核,判断移动和PC端浏览器名称,判断用户设备类型(安卓设备,iOS设备等),判断安卓IOS系统版本和做一些存在性信息校验(邮箱,邮编,电话,手机等等),还可以用于断言。他的特点有:

  • 没有任何依赖
  • 支持 AMD & CommonJS
  • 轻量级(10kb)

judge.js一个用来做判断的js类库

  • 没有任何依赖
  • 支持 AMD & CommonJS
  • 轻量级(10kb)
$ npm install  
$ gulp compress  
DEMO:http://hawx1993.github.io/jud...

开始

使用npm安装judgejs
$ npm install judgejs 
使用bower 安装judgejs
$ bower install judgejs  

目录

使用方法

var judge = require('judgejs');

judge.version

=>0.7.0

可以用$来代替judge。例如:

require('../judge.js')

$.version;
=> 0.7.0

API

数据类型判断

judge.isArray(value)
judge.isArray(['foo','bar',{'name':'trigkit4'}])

=> true
judge.isInt(num)
var num = 3.14;
judge.isInt(num);

=>false
judge.isError(value)

判断给定值是否是Error

judge.isJson(json)

判断给定值是否是json格式

 var str = '{"name":"jack"}';
 judge.isJson(str);//false
 var json = JSON.parse(str);
 judge.isJson(json);//true
judge.isFunction()

判断给定值是否是函数:

var fn = new Function ();
judge.isFunction(fn);

=>true
judge.isString()

判断一个给定的值是否是字符串,返回布尔值

judge.isObject()

判断一个给定的值是否是对象,返回布尔值;其中:
array,object,number,string,null,function,boolean被视为对象,空字符串和undefined为非对象。

var obj = Object.create(null);
judge.isObject(obj);//true

judge.isObject(undefined);//false
judge.isObjectLike(value)

判断参数value是否是object-like

judge.isObjectLike([NaN]);

=>true

judge.isObjectLike(null);

=>false
judge.type()

判断值的类型,包括:

array,object,number,string,null,undefined,function,boolean

var arr = new Array;
judge.type(arr);//array

var obj = {};
judge.type(obj);//object

var num = Number(1);
judge.type(num);//number

var str = '123';
judge.type(str);//string

var n = null;
judge.type(n);//null


var u = undefined;
judge.type(u);//undefined

var fn = function () {};
judge.type(fn);//function

var bool = Boolean();
judge.type(bool);//boolean

var proto = Object.prototype;
judge.type(proto);//object

function Person(){}
var p1 = new Person();
judge.type(p1);//object
judge.isEqual()

判断两个给定值是否是严格相等:

var judge = require('judgejs');
var str = Boolean(true);
var str2 = !!true;
var str3 = true;

var obj1 = {};
var obj2 = new Object();
var obj4 = Object.create(null);

var foo = {name:'trigkit4'};
var bar = {age:23};
var baz = Object.assign(foo,bar);
var obj3 = {
    name: 'trigkit4',
    age: 23
};
 
judge.isEqual(str,str2,str3);//true
judge.isEqual(obj1,obj2,obj4);//false
judge.isEqual(str,str2,str3);//true
judge.isEqual(baz,obj3);//false,refer address different
judge.isChar()

判断给定值是否是字符

judge.isRegExp(reg)

判断给定值是否是RegExp对象:

var reg = /^(a,z)/i;
judge.isRegExp(reg);

=> true

judge.isRegExp('/[a-z]/');

=>false
judge.isLength(value)

判断value是否是有效的类数组长度

judge.isLength(Infinity);

=>false

var arr = Number([]);
judge.isLength(arr);

>true
judge.isWindow(obj)

判断是否是window对象。

judge.isDocument()

判断是否是Document对象

judge.isPlainObject(obj)

判断obj是否是纯粹的对象,纯粹的对象是通过{}创建或者通过new Object()创建

judge.isPlainObject(window);

=>false

var arr = Number([]);
judge.isPlainObject(arr);

=>false

judge.isPlainObject(new Date());

=>false

judge.isPlainObject({});//true
judge.isArrayLike(obj)

判断obj是否是类数组对象(类数组对象被限定为拥有非负整数属性的对象,NodeList,arguments,Array等):

judge.isArrayLike(document.body.children);

=>true

var obj = [{name:'null'}];
judge.isArrayLike(obj);

=>true

judge.isArrayLike(null);

=>false
judge.isArrayLikeObject(value)

judge.isArrayLike类似,但isArrayLikeObject会检测value是否是对象

judge.isArrayLikeObject('abcd');//false
judge.isArrayLikeObject(document.body.children);//true
judge.isArguments(value)

判断参数value是否是一个arguments对象:

judge.isArguments(function(){ return arguments;}())

=>true
judge.isSet(value)

判断给定值是否不为nullundefined

judge.idNumber(id)

判断你的身份证号码是否符合规范,其中X不区分大小写:

var id = '35050019970323505x';
judge.idNumber(id);

=> true
judge.isOdd(num)

判断给定值是否是奇数,返回布尔值

judge.min(a,b)

判断给定的数值中谁是最小值,并返回最小值

judge.min(0,-1);
=>-1
judge.isEven(num)

判断一个给定的值是否是偶数,返回布尔值

$.isEven(null);

=>false
judge.isNull(value)
judge.isNull(void 0);

=>true

judge.isNull(null);

=>true
judge.isUndefined(value)
judge.isUndefined(null);

=>false

judge.isUndefined(void 0);

=>true
judge.isNumber(num)
judge.isNumber(Infinity);

=>true

平台判断

judge.kernel()

用于检测当前浏览器的内核(排版引擎),可以检测的类型如下:

webkit,gecko,trident,edge,opera
浏览器的内核分别用于检测Chrome浏览器,Firefox浏览器,IE浏览器,Edge浏览器和Opera浏览器

if(judge.kernel() == 'webkit'){...} //引号处不能出现空格等不规范写法
judge.platform()

检测用户当前设备,可以检测的类型如下:

android,iPad,ios,windowsPhone,mac,windows,linux,blackBerryandroidTablet

if(judge.platform() == "androidTablet"){...}

参数也如上所示,千万不能写错,不然检测就会出现错误。参数采用驼峰命名法

judge.browser()

检测当前浏览器类型,可以检测的类型如下:

"IE6","IE7","IE8", "IE9", "IE10", "IE11","firefox","edge","sougou","liebao","liebao mobile","weixin","uc","mobile uc","baidu browser","mobile baidu","mobile qqbrowser","qqbrowser","opera","miui browser","oppo browser","mobile safari","android chrome", "ios chrome","chrome", "safari","ios safari","Mbile IE各个版本"

如需匹配不同平台的浏览器,需用judge.platform()再做一次匹配,使用场景可以是:

1.如果没有传入参数,则返回浏览器的名称,如:

judge.browser();//你的浏览器是Chrome的话

=>Chrome

2.传入参数的情况下,返回布尔值,如:

judge.browser("isChrome");

=>true
参数如下所示,采用驼峰命名法:
"isFirefox","isIosChrome","isIpadSafari", "isEdge", "isSougou","isLiebao",
"isLiebaoMobile","isWeiXin","isUC", "isUCMobile", "isBaidu",
"isBaiduMobile", "isQQMobile","isQQBrowser", "isOpera", "isMiuiBrowser",
"isOppoBrowser","isAndroidChrome","isChrome","isIosSafari","isSafari"

其中UC浏览器采用固定大写的写法。由于有的移动端浏览器采用和浏览器不同的ua,所以不能共用(无法单纯加一个`judge.isMobile()` or `judge.platform()=='android'`)。

//IE
"isIE","isMobileIE+数字(如:isMobileIE10)","isIE+数字(6~11),如isIE10"

//for example
judge.browser("isIE11");//true,如果你的浏览器是IE11的话
judge.iosVersion()

判断iOS 系统版本号,返回数字形式的版本号:

judge.iosVersion();

=>9.0.2
judge.androidVersion()

同上

judge.isChromium()

判断用户的浏览器是否是套着chrome内核的浏览器,返回布尔值

设备判断

judge.isMobile()

判断用户设备是否是移动设备(ipad,iphone,ipod,android)

judge.isPc()

判断用户设备是否是PC

judge.iosDevice()

检测iPhone手机设备类型,可以检测如下类型的iPhone手机:

iphone4(s) ,iphone5(s), iphone6(s),iphone6(s)Plus

if(judge.iosDevice=='iphone6Plus'){...}

参数为:iphone4,iphone5,iphone6,iphone6Plus

$.iosDevice();//if your ios device is iphone6

=>iphone6 
judge.androidDevice()

检测安卓设备,现在只支持:mi4,魅族metal(mz-metal),魅族mx5,魅族mx3

TODO:准备支持更多安卓手机设备

judge.isTouchDevice()

判断用户当前设备是否是触屏设备,返回布尔值Boolean

存在性和信息校验

judge.isExist(value)
var str =  null;
judge.isExist(str)
=>false

var str = '';
judge.isExist(str)
=>false
judge.lt(val1,val2)

判断val1是否小于val2:

judge.lt(1,-2);

=>false
judge.inArray(val,arr)

判断参数val是否存在arr数组内:

var val = [{'name':'huang'},123],
    arr = [val,456];
judge.inArray(val,arr);

=>true
judge.email(em)

判断是否符合Email规范:

var email = 'hwx.trigkit4@163.com';
judge.email(email);

=>true

var email2 = 'hwx.trigkit.@gmail.com';
judge.email(email2);
=>false
judge.hasLowerCase()

判断是否含有小写字母:

var str ='trigkit4';
judge.hasLowerCase(str);
judge.hasNumber()

判断给定值是否含有数字:

var num ='trigkit4';
judge.hasNumber(num);

=>true
judge.hasCaptial()

判断是否含有大写字母:

var str ='trigkit4';
judge.hasCapital(str);
judge.isBrowser()

判断当前客户端是否是浏览器,返回布尔值

judge.size(val)

判断给定值的大小,返回数值:

var val = '琅琊榜lyb';
judge.size(val);

=>6
judge.isHttps()

判断当前站点是否是HTTPS,返回布尔值

judge.isUnique()

判断一个给定数组的元素的值是否唯一:

var a = [1,2];
var arr = [1,2,3,4,a];//[1,2,3,4,[1,2]];
judge.isUnique(arr);//true

var arary = ['1',1];
judge.isUnique(array);//true
judge.hasClass()

判断给定值是否有class

judge.qqNumber()

判断给定值是否符合QQ号规范,返回布尔值:

var qq = 345812345;
judge.qqNumber(qq);

=>true
judge.phoneNumber

判断给定值是否符合手机号规范:

var num = 17755503789;
judge.phoneNumber(num);

=>true
judge.telPhone(num)

判断电话号码是否符合规范

judge.includeChinese

判断给定值是否含有中文字符:

var ch = 'js脚本';
judge.includeChinese(ch);

=> true
judge.onlyChinese(ch)

判断给定字符是否仅有中文字符:

var ch = 'zh中国';
judge.onlyChinese(ch);

=>false
judge.onlyNumber()

判断给定值是否只含有数字:

var s = '233';
judge.onlyNumber(s);

=>true
judge.isElement(element)

判断给定元素是否是DOM元素,返回布尔值

var div = document.createElement('div');
judge.isElement(div);

=>true
judge.assert(value,desc)

你可以使用judge.assert 去断言你想要断言的值,如果该值通过断言,描述不符将变为绿色,否则变为红色;

function add(a,b){
    return a + b;
}
var a = 1,b=2;

judge.assert(add(1,2) === 3,'true');
judge.assert(add(2,3) === 6,'false');

在参数desc 部分去填写你的测试描述

judge.hasHash(url)

判断一个给定的url是否有哈希值

var url = 'www.baidu.com#w';
judge.hasHash(url);

=> true
judge.has(obj,key)

判断obj是否有包含给定的键(key)


var obj ={
    name:'trigkit4'
};
judge.has(obj,'name');

=>true
judge.isUrl(url)

判断一个给定的值是否是URL


var url = 'www.jd.d';
judge.isUrl(url);

=>false
judge.zipCode(code)

判断给定值是否符合邮编规范:

var zipcode = 362014;
judge.zipCode(zipcode);

=>true
judge.include(str,substr)
var str =  'microsoft';
var substr = 'soft';
judge.include(str,substr);

=>true
judge.isOnline()

可用于判断设备是否联网,判断断网可用judge.isOnline==false,返回true,即断网

judge.hasSpecialChar()

判断是否含有特殊字符,除了大小写字母、数字和汉字以外的字符都被视为特殊字符

var char = 'a!@#$%';
judge.hasSpecialChar(char);

=>true
judge.isEmpty()

判断给定值是否为空,nullundefined被视为空,
数字0被视为非空

var arr = [];//judge.isEmpty(arr); => true
var n = null;//judge.isEmpty(n); => true
var u = undefined;//judge.isEmpty(u); => true
var num = 0;//judge.isEmpty(num); => false
var obj = Object.create(null);//judge.isEmpty(obj); => true
var str = '';//judge.isEmpty(str); => true
judge.position(element,parent)

判断DOM元素位置,若只传入element参数,则返回其距离浏览器窗口的位置;
若传入parent参数,则返回其距离父元素的位置。兼容IE浏览器

@{param}:parent 可选

judge.position(element).top ;//判断元素距离顶部位置
judge.position(element,parent).left;//判断元素距离父元素左边的位置
judge.isNativeFn(fn)

判断fn是否是原生方法,不能有括号

judge.isNativeFn(Object.assign);

=>true


var fn = new Function();
judge.isNativeFn(fn);

=>false


judge.isNativeFn(Array.prototype.filter)

=>true

var obj = {
        fn: function () {}
 };
 
judge.isNativeFn(obj.fn)

=>false
judge.isIE8Plus(boolean)

判断当前浏览器是否是IE8+ (包含IE8),直接返回布尔值

参数如下:

  • true:包含IE8
judge.isIE8Plus(true);//include IE8
  • false:不包含IE8

judge.isIE8Plus(false);//exclude IE8

没有参数,默认包含IE8

judge.strLength(str)

判断字符长度,返回数字。一个中文字符被视为2,一个英文字符为视为1:

judge.strLength('你好China');//9
judge.isLeapYear(year)

判断是否是闰年

查看原文

majormayer 回答了问题 · 2020-01-31

解决C# 启动本地图片服务

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Web;

using Westwind.Utilities;

namespace Infrastructure.SelfHost
{
    /// <summary>
    /// A simple self-contained static file Web Server that can be
    /// launched in a folder with a port and serve static files
    /// from that folder. Very basic features but easy to integrate.
    /// </summary>
    /// <example>
    /// StartHttpServerOnThread(@"c:\temp\http",8080);
    /// ...
    /// StopHttpServerOnThread();
    /// </example>
    /// <remarks>
    /// Based mostly on:
    /// https://gist.github.com/aksakalli/9191056
    /// 
    /// Additions to make it easier to host server inside of an
    /// external, non-.NET application.
    ///</remarks>

    public class SimpleHttpServer
    {
        public string[] DefaultDocuments =
        {
            "index.html",
            "index.htm",
            "default.html",
            "default.htm"
        };

        public static SimpleHttpServer Current;

        /// <summary>
        /// This method can be used externally to start a singleton instance of 
        /// the Web Server and keep it running without tracking a reference.                
        /// 
        /// If a server instance is already running it's shut down.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="port"></param>        
        /// <param name="requestHandler">
        /// Optional parameter of an object that has a Process method that gets passed a context 
        /// and returns true if the request is handled or false if default processing should occur
        /// </param>
        public static void StartHttpServerOnThread(string path, int port = 8080, object requestHandler = null)
        {
            var t = new Thread(StartHttpServerThread);
            t.SetApartmentState(ApartmentState.STA);
            t.Start(new ServerStartParameters { Path = path, Port = port, RequestHandler = requestHandler });
        }

        /// <summary>
        /// Call this method to stop the Singleton instance of the server.
        /// </summary>
        public static void StopHttpServerOnThread()
        {
            Current.Stop();
            Current = null;
        }


        /// <summary>
        /// Internal method that instantiates the server instance
        /// </summary>
        /// <param name="parms"></param>
        private static void StartHttpServerThread(object parms)
        {

            if (Current != null)
                StopHttpServerOnThread();

            var httpParms = parms as ServerStartParameters;
            Current = new SimpleHttpServer(httpParms.Path, httpParms.Port);
            Current.RequestHandler = httpParms.RequestHandler;
        }


        /// <summary>
        /// Mime Type conversion table
        /// </summary>
        private static IDictionary<string, string> _mimeTypeMappings =
            new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
            {
                #region extension to MIME type list
                {".asf", "video/x-ms-asf"},
                {".asx", "video/x-ms-asf"},
                {".avi", "video/x-msvideo"},
                {".bin", "application/octet-stream"},
                {".cco", "application/x-cocoa"},
                {".crt", "application/x-x509-ca-cert"},
                {".css", "text/css"},
                {".deb", "application/octet-stream"},
                {".der", "application/x-x509-ca-cert"},
                {".dll", "application/octet-stream"},
                {".dmg", "application/octet-stream"},
                {".ear", "application/java-archive"},
                {".eot", "application/octet-stream"},
                {".exe", "application/octet-stream"},
                {".flv", "video/x-flv"},
                {".gif", "image/gif"},
                {".hqx", "application/mac-binhex40"},
                {".htc", "text/x-component"},
                {".htm", "text/html"},
                {".html", "text/html"},
                {".ico", "image/x-icon"},
                {".img", "application/octet-stream"},
                {".iso", "application/octet-stream"},
                {".jar", "application/java-archive"},
                {".jardiff", "application/x-java-archive-diff"},
                {".jng", "image/x-jng"},
                {".jnlp", "application/x-java-jnlp-file"},
                {".jpeg", "image/jpeg"},
                {".jpg", "image/jpeg"},
                {".js", "application/x-javascript"},
                {".mml", "text/mathml"},
                {".mng", "video/x-mng"},
                {".mov", "video/quicktime"},
                {".mp3", "audio/mpeg"},
                {".mpeg", "video/mpeg"},
                {".mpg", "video/mpeg"},
                {".msi", "application/octet-stream"},
                {".msm", "application/octet-stream"},
                {".msp", "application/octet-stream"},
                {".pdb", "application/x-pilot"},
                {".pdf", "application/pdf"},
                {".pem", "application/x-x509-ca-cert"},
                {".pl", "application/x-perl"},
                {".pm", "application/x-perl"},
                {".png", "image/png"},
                {".prc", "application/x-pilot"},
                {".ra", "audio/x-realaudio"},
                {".rar", "application/x-rar-compressed"},
                {".rpm", "application/x-redhat-package-manager"},
                {".rss", "text/xml"},
                {".run", "application/x-makeself"},
                {".sea", "application/x-sea"},
                {".shtml", "text/html"},
                {".sit", "application/x-stuffit"},
                {".swf", "application/x-shockwave-flash"},
                {".tcl", "application/x-tcl"},
                {".tk", "application/x-tcl"},
                {".txt", "text/plain"},
                {".war", "application/java-archive"},
                {".wbmp", "image/vnd.wap.wbmp"},
                {".wmv", "video/x-ms-wmv"},
                {".xml", "text/xml"},
                {".xpi", "application/x-xpinstall"},
                {".zip", "application/zip"},

                #endregion
            };

        private Thread _serverThread;
        private string _rootDirectory;
        private HttpListener _listener;
        private int _port;

        public int Port
        {
            get { return _port; }
        }


        /// <summary>
        /// Instance of an object whose Process() method is called on each request.
        /// Return true if the reuqest is handled, fase if it's not.
        /// </summary>
        public object RequestHandler { get; set; }

        /// <summary>
        /// Construct server with given port.
        /// </summary>
        /// <param name="path">Directory path to serve.</param>
        /// <param name="port">Port of the server.</param>
        public SimpleHttpServer(string path, int port = 8080)
        {
            Initialize(path, port);
        }

        /// <summary>
        /// Construct server with suitable port.
        /// </summary>
        /// <param name="path">Directory path to serve.</param>
        public SimpleHttpServer(string path)
        {
            //get an empty port
            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
            listener.Start();
            int port = ((IPEndPoint)listener.LocalEndpoint).Port;
            listener.Stop();

            Initialize(path, port);
        }

        /// <summary>
        /// Stop server and dispose all functions.
        /// </summary>
        public void Stop()
        {
            _serverThread.Abort();
            _listener.Stop();
        }

        /// <summary>
        /// Internal Handler
        /// </summary>
        private void Listen()
        {
            _listener = new HttpListener();
            _listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
            _listener.Start();

            while (true)
            {
                try
                {
                    HttpListenerContext context = _listener.GetContext();
                    Process(context);
                }
                catch (Exception ex)
                {

                }
            }
        }


        /// <summary>
        /// Process an individual request. Handles only static file based requests
        /// </summary>
        /// <param name="context"></param>
        private void Process(HttpListenerContext context)
        {
            string filename = HttpUtility.UrlDecode(context.Request.Url.AbsolutePath);
            Console.WriteLine(filename);

            if (RequestHandler != null)
            {
                if ((bool)ReflectionUtils.CallMethodCom(RequestHandler, "Process", context))
                    return;
            }

            filename = filename.Substring(1);

            if (string.IsNullOrEmpty(filename))
            {
                foreach (string indexFile in DefaultDocuments)
                {
                    if (File.Exists(Path.Combine(_rootDirectory, indexFile)))
                    {
                        filename = indexFile;
                        break;
                    }
                }
            }


            filename = Path.Combine(_rootDirectory, filename);

            if (File.Exists(filename))
            {
                try
                {
                    Stream input = new FileStream(filename, FileMode.Open);

                    //Adding permanent http response headers
                    string mime;
                    context.Response.ContentType = _mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime)
                        ? mime
                        : "application/octet-stream";
                    context.Response.ContentLength64 = input.Length;
                    context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                    context.Response.AddHeader("Last-Modified", File.GetLastWriteTime(filename).ToString("r"));

                    byte[] buffer = new byte[1024 * 32];
                    int nbytes;
                    while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
                        context.Response.OutputStream.Write(buffer, 0, nbytes);
                    input.Close();
                    context.Response.OutputStream.Flush();

                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                }
                catch (Exception ex)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                }

            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }

            context.Response.OutputStream.Close();
        }

        private void Initialize(string path, int port)
        {
            _rootDirectory = path;
            _port = port;
            _serverThread = new Thread(Listen);
            _serverThread.Start();
        }


    }

    /// <summary>
    /// Parameters thatr are passed to the thread method
    /// </summary>
    public class ServerStartParameters
    {
        public string Path { get; set; }
        public int Port { get; set; }

        /// <summary>
        ///  Any object that implements a Process method
        ///  method should return true (request is handled) 
        /// or false (to fall through and handle as files)
        /// </summary>
        public object RequestHandler { get; set; }
    }

}

关注 1 回答 1

majormayer 提出了问题 · 2020-01-31

解决C# 启动本地图片服务

图片.png
如上图 , 在windows电脑上有下面文件夹 , 内容均为图片

使用C#如何实现在当前文件夹启动一个简单的http服务,以实现,在局域网下手机app中直接读取图片,如:
<img data-original='http://192.168.1.14:30001/Slideimages/幻灯片1.PNG'>

关注 1 回答 1

majormayer 关注了问题 · 2019-12-25

golang mysql Scan操作按顺序取值问题

rows, err := db.Query("SELECT * FROM user")
checkErr(err)
 
for rows.Next() {
    var userId int
    var userName string
    var userAge int
    var userSex int
    rows.Columns()
    err = rows.Scan(&userId, &userName, &userAge, &userSex)
    checkErr(err)
    fmt.Println(userId)
    fmt.Println(userName)
    fmt.Println(userAge)
    fmt.Println(userSex)
}

如果这时候操作数据在userName前面新增一个字段
这段代码岂不是就废了
在项目中会这样写吗?

关注 7 回答 5

majormayer 赞了问题 · 2019-12-25

golang mysql Scan操作按顺序取值问题

rows, err := db.Query("SELECT * FROM user")
checkErr(err)
 
for rows.Next() {
    var userId int
    var userName string
    var userAge int
    var userSex int
    rows.Columns()
    err = rows.Scan(&userId, &userName, &userAge, &userSex)
    checkErr(err)
    fmt.Println(userId)
    fmt.Println(userName)
    fmt.Println(userAge)
    fmt.Println(userSex)
}

如果这时候操作数据在userName前面新增一个字段
这段代码岂不是就废了
在项目中会这样写吗?

关注 7 回答 5

majormayer 赞了问题 · 2019-12-17

moment日期比较

请问如何比较两个时间的大小

比如 2016-05-04 和 2016-05-16
一 、 moment(' 2016-05-04')>moment('2016-05-16')返回false

关注 3 回答 2

majormayer 赞了回答 · 2019-12-17

moment日期比较

moment('2016-05-04').isBefore('2016-05-16')

就不能去看看API么???

关注 3 回答 2

majormayer 回答了问题 · 2019-12-03

Word 2010 ,双击打开带 word addin 项目数据的docx文档 不能正确加载数据

这是我封装的在PPT中插入元素的cs代码,没做整理,供参考:

using System;
using System.IO;

using Infrastructure;
using Infrastructure.FileHelper;

using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;

using VarEnum;

using Shape = Microsoft.Office.Interop.PowerPoint.Shape;
using Word = Microsoft.Office.Interop.Word;

namespace PowerPointAddIn.Vstor
{
    /// <summary>
    /// 幻灯片扩展_插入元素
    /// </summary>
    public static class InsertElement
    {
        static Word.Application wordApp;
        static Word.Document wordDoc;
        static Word.ContentControl contentControl;
        //public enum AddPictureType
        //{
        //    常规, 有题可推, 未初始化
        //}

        ///// <summary>
        ///// 添加图片
        ///// </summary>
        ///// <param name="slide"></param>
        //public static void AddPicture(Slide slide, string filePath)
        //{

        //}

        /// <summary>
        /// 添加媒体
        /// </summary>
        public static void AddMedia(Slide slide, string filePath)
        {
            if (!File.Exists(filePath))
                return;

            try
            {
                Shape pic = slide.Shapes.AddMediaObject2(filePath, MsoTriState.msoFalse, MsoTriState.msoTrue);
            }
            catch
            {
                string ext = Path.GetExtension(filePath).Replace(".", string.Empty);
                throw new Exception("暂不支持此[" + ext + "]格式添加到PPT");
            }
        }

        /// <summary>
        /// 添加http
        /// </summary>
        public static void AddHttp(Slide slide, string filePath)
        {
            if (!File.Exists(filePath))
                return;

            Shape pic = slide.Shapes.AddOLEObject(FileName: filePath);
        }

        #region 富文本
        /// <summary>
        /// 插入富文本 (使用word剪切板实现 有很大风险  暂时弃用)
        /// </summary>
        public static async void InsertRich(this Slide slide, string html)
        {
            //插入富文本控件
            try
            {
                wordApp = wordApp ?? new Word.Application();
                wordDoc = wordDoc ?? wordApp.Documents.Add();
                contentControl = contentControl ?? wordDoc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText);

                string path = await HtmlHelper.Save2TempFile(html);

                contentControl.Range.InsertFile(path);
                contentControl.Range.Copy();

                ThisAddIn.application.ActiveWindow.View.PasteSpecial();
            }
            finally
            {
                contentControl.Range.Delete();
            }
        }
        #endregion

        #region 图片
        /// <summary>
        /// 插入图片
        /// </summary>
        /// <param name="slide"></param>
        /// <param name="filePath"></param>
        /// <param name="idName">这张图片的唯一名字</param>
        public static void AddPicture(this Slide slide, string filePath, string name = "", int height = -1, int width = -1, int top = 0, int left = 0)
        {
            //没有设置宽高使用图片原始大小插入
            Shape pic;
            if (height > 0 || width > 0)
                pic = slide.Shapes.AddPicture(filePath, MsoTriState.msoFalse, MsoTriState.msoTrue, left, top, width, height);
            else
                pic = slide.Shapes.AddPicture(filePath, MsoTriState.msoFalse, MsoTriState.msoTrue, left, top);

            pic.Name = name;
            pic.Left = left;
            pic.Top = top;
            pic.Width = width;
            pic.Height = height;
        }

        /// <summary>
        /// 移除形状 包含(图片)
        /// </summary>
        /// <param name="slide"></param>
        /// <param name="name"></param>
        public static void DeletePicture(this Slide slide, string name)
        {
            try
            {
                var Shape = slide.Shapes.Range(name);
                Shape.Delete();
            }
            catch { }
        }
        #endregion
    }
}

关注 1 回答 2

majormayer 回答了问题 · 2019-12-03

解决vsto PPT插件开发,往右键菜单添加自定义按钮,出现兼容问题,我在自己的电脑上开发,没有出现错误异常,在客户电脑上出现这个错

已解决,没有整理,直接贴上实现的代码:

using Application.BaseData;
using Application.Config;

using Common.Logging;

using Infrastructure;

using Microsoft.Office.Core;

using stdole;

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Util.Controls.WinForm;

using Utilities.Converter;

using VarEnum;

using WpfUi.View.MaterialSet;
using WpfUi.ViewModel.MaterialSet;
using WpfUi.ViewModel.MaterialSet.Model;

namespace PowerPointAddIn.Vstor
{
    /// <summary>
    /// 操作扩展
    /// </summary>
    public class ContextMenuEx
    {
        private static readonly ILog _log = LogManager.GetLogger("ContextMenuEx");

        readonly CommandBars cmdBars;
        readonly CommandBar cmdThumbnailsBar;

        CommandBarButton insertResourceBtn = null;

        public ContextMenuEx()
        {
            try
            {
                cmdBars = ThisAddIn.application.CommandBars;
                cmdThumbnailsBar = cmdBars[ThisAddIn.officeType == OfficeType.Office ? "Thumbnails" : "Slide Miniature Popup Menu"];
                cmdThumbnailsBar.Reset();

                SetInsertResource();
            }
            catch (Exception err)
            {
                _log.Error(err);
            }
        }
        /// <summary>
        ///  设置素材插入
        /// </summary>
        public void SetInsertResource()
        {
            CommandBarControls commandBarControls = cmdThumbnailsBar.Controls;

            foreach (CommandBarControl cmdBarCtrl in commandBarControls)
                if (cmdBarCtrl.Tag == "InsertResource")
                    cmdBarCtrl?.Delete();

            string icon_stem = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"Resources\icon-sucai32.png");
            IPictureDisp pictureInsertResource = AxHostConverter.GetIPictureDisp(icon_stem);

            Globals.ThisAddIn.Dispatcher.Invoke(() =>
            {
                insertResourceBtn = (CommandBarButton)commandBarControls.Add(MsoControlType.msoControlButton);
                insertResourceBtn.BeginGroup = true;
                insertResourceBtn.Tag = "InsertResource";
                insertResourceBtn.Caption = "从云端插入";
                insertResourceBtn.Picture = pictureInsertResource;
                insertResourceBtn.Click += InsertResourceBtn_Click;
                insertResourceBtn.Visible = true;
            });
        }

        /// <summary>
        /// 切换素材插入
        /// </summary>
        /// <param name="state">切换状态</param>
        public void SwitchInsertResource(bool state)
        {
            if (insertResourceBtn == null) return;
            try
            {
                insertResourceBtn.Visible = state;
            }
            catch (Exception err)
            {
                _log.Error(err);
            }
        }

        private void InsertResourceBtn_Click(CommandBarButton Ctrl, ref bool CancelDefault)
        {
            try
            {
                if (string.IsNullOrEmpty(Config.UserInfo?.UserId))
                    throw new Exception("请先登录")
                    {
                        Source = Envirment.ErrUiSource
                    };

                var viewMode = new MaterialSetViewModel(new BaseDataApplication(), Config.UserInfo.UserId, Config.SchoolCode);
                viewMode.InsertElement2Slide += InsertElement2Slide;
                viewMode.SetWindow(new MaterialSetView());
                ThisAddIn.Show(viewMode.Window);
            }
            catch (Exception err)
            {
                Ex.GlobalUnCatchError(err);
            }
        }


        void InsertElement2Slide(List<Material> ChooseMaterials)
        {
            if (ChooseMaterials?.Count < 1)
                return;

            PptHelp pptHelp = new PptHelp();
            try
            {
                ChooseMaterials.ForEach(p =>
                {
                    if (!InternetHelp.IsFileOrExt(p.MaterialUrl, out string ext))
                    {
                        ThisAddIn.ShowDialog(new Resource.Control.AlertWin.alertWindow(new
                        {
                            message = "不是有效的文件[" + p.Name + "],导入失败",
                        }));
                        return;
                    }

                    if (p.MaterialType == MaterialType.图片)
                    {
                        pptHelp.AddImg(p.MaterialUrl);
                    }
                    else if (p.MaterialType == MaterialType.音频 || p.MaterialType == MaterialType.视频)
                    {
                        if (string.IsNullOrEmpty(ext))
                        {
                            ThisAddIn.ShowDialog(new Resource.Control.AlertWin.alertWindow(new
                            {
                                message = "不能识别此文件[" + p.Name + "]的格式,导入失败",
                            }));
                            return;
                        }

                        string fileName = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetRandomFileName(), ext));

                        FormDownload formDownload = new FormDownload(new Uri(p.MaterialUrl), fileName);
                        formDownload.ShowDialog();

                        pptHelp.AddMedia(fileName);

                        Task.Run(() =>
                        {
                            try
                            {
                                if (File.Exists(fileName))
                                {
                                    File.Delete(fileName);
                                }
                            }
                            catch { }
                        });

                    }
                });
            }
            catch (Exception ex)
            {
                ThisAddIn.ShowDialog(new Resource.Control.AlertWin.alertWindow(new
                {
                    message = ex.Message,
                }));
            }
        }
    }
}

关注 2 回答 2

认证与成就

  • 获得 67 次点赞
  • 获得 162 枚徽章 获得 9 枚金徽章, 获得 54 枚银徽章, 获得 99 枚铜徽章

擅长技能
编辑

开源项目 & 著作
编辑

  • MajorUI

    MajorUI是一个基于Do平台的快速APP跨平台开发的UI框架

注册于 2016-02-15
个人主页被 1.8k 人浏览