Exemplo n.º 1
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            ValidationHelper.NotNull(serviceProvider, "serviceProvider");
            var rootObjectProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;

            if (rootObjectProvider == null)
            {
                throw new InvalidOperationException(string.Format(ServiceException, GetType().Name, "IRootObjectProvider"));
            }
            if (rootObjectProvider.RootObject is ResourceDictionary)
            {
                var ret1 = StaticResource.ProvideValue(serviceProvider);
                return(ret1);
            }
            var themeInfo = ResourceInfoAttribute.FromAssembly(rootObjectProvider.RootObject.GetType().Assembly);

            if (themeInfo != null)
            {
                switch (themeInfo.Mode)
                {
                case ResourceMode.Static:
                    var ret2 = StaticResource.ProvideValue(serviceProvider);
                    return(ret2);

                case ResourceMode.Dynamic:
                    var ret3 = DynamicResource.ProvideValue(serviceProvider);
                    return(ret3);
                }
            }
            throw new InvalidOperationException("You must mark your assembly with Elysium.ResourceInfo attribute or use Elysium.ResourceDictionary");
        }
Exemplo n.º 2
0
        private async void DismissExtendedSplash()
        {
            Window.Current.SizeChanged -= ExtendedSplash_OnResize;
            StateText = "正在检查后台通知";
            await BackgroundHelper.Register <UpdateUnreadCountTask>(new TimeTrigger(15, false));

            await BackgroundHelper.Register <ToastNotificationBackgroundTask>(new ToastNotificationActionTrigger());

            StateText = "正在初始化表情";
            await StaticResource.InitEmotion();

            var cahcesize = rootFrame.CacheSize;

            rootFrame.CacheSize = 0;
            rootFrame.CacheSize = cahcesize;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            StateText = "正在初始化用户数据";
            if (await StaticResource.CheckForLogin())
            {
                await InitUid();

                rootFrame.Navigate(typeof(MainPage));
            }
            else
            {
                rootFrame.Navigate(typeof(LoginPage));
            }
            SystemNavigationManager.GetForCurrentView().BackRequested += ExtendedSplash_BackRequested;
            rootFrame.Navigated   += RootFrame_Navigated;
            Window.Current.Content = rootFrame;
        }
Exemplo n.º 3
0
 public static void ReloadUserImageBuffer()
 {
     //加载用户头像缓存
     foreach (String ui in IoTool.GetFiles(StaticResource.UserHeadImageBasePath))
     {
         long   loginnum = 0;
         String fn       = IoTool.GetFileName(ui);
         if (long.TryParse(fn, out loginnum))
         {
             StaticResource.SetHeadImageSource(loginnum, ImageTool.GetUserHeadeImage(loginnum));
         }
     }
 }
        public static Func <NancyContext, string, Response> MapFile(string virtualPath, string embeddedResourceName, Assembly assemblyContainingResource)
        {
            Dictionary <string, StaticResource> responders = new Dictionary <string, StaticResource>(StringComparer.OrdinalIgnoreCase);

            virtualPath = virtualPath.TrimStart('/').Replace("/", ".");
            StaticResource staticResource = new StaticResource
            {
                ManifestResourceName = embeddedResourceName,
                MimeType             = MimeTypes.GetMimeType(embeddedResourceName)
            };

            responders.Add(virtualPath, staticResource);

            return(new EmbeddedStaticContentConventionBuilder(assemblyContainingResource, responders).Respond);
        }
Exemplo n.º 5
0
 //如果登录成功
 public void OnLoginSuccess(User u)
 {
     StaticResource.ALLUserSource = u;
     StartDoubleAnima(WidthProperty, 0, "0:0:1");
     Thread.Sleep(700);
     ImageTool.GetUserHeadImage(u.UloginNumber ?? 0);
     u.UheadImage = StaticResource.ToUserHeadImagePath(u.UloginNumber.ToString() + ".png");
     Dispatcher.Invoke(() =>
     {
         new UserListForm(StaticResource.ALLUserSource).Show();
         StaticResource.SetHeadImageSource(u.UloginNumber ?? 0, ImageTool.GetUserHeadeImage(u.UloginNumber ?? 0));
         Hide();
         OnlineSendThread = new Thread(() =>
         {
             while (true)
             {
                 Thread.Sleep(OnLineTokenSendTime * 1000);
                 SocketClient.SendTo(new MessageModel(MessageType.Login, u.UloginNumber ?? 0, 0, SocketTool.IPV4Address.ToString(), new MessageContent_Login()
                 {
                     Content         = MessageModel.ToBytes(u),
                     LoginType       = LoginType.ImOnline,
                     RequestDateTime = DateTime.Now.ToString(),
                     WithMessage     = ""
                 }), StaticResource.ServerIpaddress);
             }
         });
         OnlineSendThread.Start();
         SocketClient.GetNewMessage -= SocketClient_GetNewMessage;
         //添加一项登录记录
         if (!CB_IsSavePassword.IsChecked ?? false)
         {
             u.Upassword = "";
         }
         foreach (User tu in (List <User>)TEXT_LoginNumber.ItemsSource)
         {
             XMLLoginLog.SelectALL(sn =>
             {
                 if (sn["Uid"].InnerText == u.Uid.ToString())
                 {
                     XMLLoginLog.Body.RemoveChild(sn);
                     return;
                 }
             });
         }
         XMLLoginLog.Body.AppendChild(XMLLoginLog.ModelToNode(u));
         XMLLoginLog.Save();
     });
 }
Exemplo n.º 6
0
        private StaticResource CreateStaticResource(string fullPath, string app, string extensionName, string fileName, string reName, string filePath, FileConfig config)
        {
            FileInfo fileInfo = new FileInfo(fullPath);
            //正式文件入库
            StaticResource sr = new StaticResource();

            sr.App        = app;
            sr.Extension  = extensionName;
            sr.FilePath   = fullPath;
            sr.FileSize   = fileInfo.Length;
            sr.Guid       = Guid.NewGuid().ToString();
            sr.UploadTime = DateTime.Now;
            sr.HttpURL    = "";
            sr.Name       = fileName;
            sr.VirtualURL = (filePath.Replace(config.ParentPath, "/").Replace("\\", "/") + "/" + reName);

            return(sr);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 静态资源文件上传
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Result <StaticResource> AddStaticResource(StaticResource model)
        {
            Result <StaticResource> result = new Result <StaticResource>();

            try
            {
                dbContext.StaticResource.Add(model);
                dbContext.SaveChanges();
                result.Data = model;
                result.Flag = EResultFlag.Success;
            }
            catch (Exception ex)
            {
                result.Data      = null;
                result.Flag      = EResultFlag.Failure;
                result.Exception = new ExceptionEx(ex, "AddStaticResource");
            }
            return(result);
        }
        public static void Build(BusinessDbContext db)
        {
            var resourceBinders = StaticResource.GetResources();

            if (!db.Resources.Any())
            {
                foreach (var resourceBinder in resourceBinders)
                {
                    var resource = new Resource
                    {
                        Id            = Guid.NewGuid().ToString(),
                        Name          = resourceBinder.Name,
                        Route         = resourceBinder.State,
                        IsPublic      = resourceBinder.IsPublic,
                        Order         = resourceBinder.Order,
                        DisplayName   = resourceBinder.DisplayName,
                        ResourceOwner = resourceBinder.ResourceOwner,
                        ParentRoute   = resourceBinder.ParentState
                    };
                    db.Resources.Add(resource);
                }
                db.SaveChanges();
            }
            else
            {
                foreach (var resourceBinder in resourceBinders.Where(resource => db.Resources.FirstOrDefault(x => x.Route == resource.State) == null))
                {
                    var resource = new Resource
                    {
                        Id            = Guid.NewGuid().ToString(),
                        Name          = resourceBinder.Name,
                        Route         = resourceBinder.State,
                        IsPublic      = resourceBinder.IsPublic,
                        Order         = resourceBinder.Order,
                        DisplayName   = resourceBinder.DisplayName,
                        ResourceOwner = resourceBinder.ResourceOwner,
                        ParentRoute   = resourceBinder.ParentState
                    };
                    db.Resources.Add(resource);
                }
                db.SaveChanges();
            }
        }
        private static Dictionary <string, StaticResource> LoadResources(Assembly assembly, string resourceNamespaceRoot, string virtualDirectory)
        {
            virtualDirectory = virtualDirectory.TrimStart('/', '.');
            Dictionary <string, StaticResource> dictionary = new Dictionary <string, StaticResource>(StringComparer.OrdinalIgnoreCase);

            foreach (string str in assembly.GetManifestResourceNames())
            {
                if (str.StartsWith(resourceNamespaceRoot, StringComparison.OrdinalIgnoreCase))
                {
                    string         key            = (virtualDirectory + str.Substring(resourceNamespaceRoot.Length).Replace("/", ".")).TrimStart('/', '.');
                    StaticResource staticResource = new StaticResource
                    {
                        ManifestResourceName = str,
                        MimeType             = MimeTypes.GetMimeType(str)
                    };
                    dictionary.Add(key, staticResource);
                }
            }
            return(dictionary);
        }
Exemplo n.º 10
0
        protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
        {
            var frame = Window.Current.Content as Frame ?? new Frame();

            Window.Current.Content = frame;
            if (Core.Api.Entity.AccessToken == null)
            {
                Core.Api.Entity.AccessToken = SettingHelper.GetListSetting <string>(SettingNames.AccessToken).ToList()[Settings.SelectedUserIndex];
            }
            if (StaticResource.Emotions == null)
            {
                await StaticResource.InitEmotion();
            }
            frame.Navigate(typeof(PostWeiboPage), new Common.Entities.PostWeibo());
            //ShareOperation shareOperation = args.ShareOperation;
            //if (shareOperation.Data.Contains(StandardDataFormats.Text))
            //{
            //    string text = await shareOperation.Data.GetTextAsync();
            //    frame.Navigate(typeof(PostWeiboPage), new Common.Entities.SharedPostWeibo() { Data = text, Operation = shareOperation });
            //    shareOperation.ReportDataRetrieved();
            //}
            //else if (shareOperation.Data.Contains(StandardDataFormats.Bitmap))
            //{
            //    var bitmap = await shareOperation.Data.GetBitmapAsync();
            //    using (var stream = await bitmap.OpenReadAsync())
            //    {
            //        byte[] bytes = new byte[stream.Size];
            //        var buffer = await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
            //        bytes = buffer.ToArray();
            //        frame.Navigate(typeof(PostWeiboPage), new Common.Entities.SharedPostWeibo() { ImageData = bytes, Operation = shareOperation });
            //    }
            //    shareOperation.ReportDataRetrieved();
            //}
            //else if (shareOperation.Data.Contains(StandardDataFormats.StorageItems))
            //{
            //    var files = await shareOperation.Data.GetStorageItemsAsync();
            //    frame.Navigate(typeof(PostWeiboPage), new Common.Entities.SharedPostWeibo() { Operation = shareOperation, ImageFiles = files });
            //}
            Window.Current.Activate();
        }
Exemplo n.º 11
0
        /// <inheritdoc />
        protected virtual async void ShowIcon(Microsoft.Media.Advertising.Icon icon, StaticResource staticResource, CancellationTokenSource cts)
        {
            if (icon.Offset.HasValue)
            {
                try
                {
#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
                    await TaskEx.Delay((int)icon.Offset.Value.TotalMilliseconds, cts.Token);
#else
                    await Task.Delay((int)icon.Offset.Value.TotalMilliseconds, cts.Token);
#endif
                }
                catch (OperationCanceledException) { /* swallow */ }
            }

            if (!cts.IsCancellationRequested)
            {
                var iconHost = new HyperlinkButton();
                iconHost.NavigateUri = icon.ClickThrough;

                double topMargin  = 0;
                double leftMargin = 0;
                if (icon.Width.HasValue)
                {
                    iconHost.Width = icon.Width.Value;
                }
                if (icon.Height.HasValue)
                {
                    iconHost.Height = icon.Height.Value;
                }
                switch (icon.XPosition)
                {
                case "left":
                    iconHost.HorizontalAlignment = HorizontalAlignment.Left;
                    break;

                case "right":
                    iconHost.HorizontalAlignment = HorizontalAlignment.Right;
                    break;

                default:
                    iconHost.HorizontalAlignment = HorizontalAlignment.Left;
                    int xPositionValue;
                    if (int.TryParse(icon.XPosition, out xPositionValue))
                    {
                        leftMargin = xPositionValue;
                    }
                    break;
                }
                switch (icon.YPosition)
                {
                case "top":
                    iconHost.VerticalAlignment = VerticalAlignment.Top;
                    break;

                case "bottom":
                    iconHost.VerticalAlignment = VerticalAlignment.Bottom;
                    break;

                default:
                    iconHost.VerticalAlignment = VerticalAlignment.Top;
                    int yPositionValue;
                    if (int.TryParse(icon.YPosition, out yPositionValue))
                    {
                        topMargin = yPositionValue;
                    }
                    break;
                }
                iconHost.Margin = new Thickness(leftMargin, topMargin, 0, 0);

                var iconElement = new Image();
                iconElement.Stretch = Stretch.Fill;
                iconElement.Source  = new BitmapImage(staticResource.Value);
                iconHost.Content    = iconElement;

                //TODO: avoid visually overlaping icons

                iconHost.Tag    = icon;
                iconElement.Tag = icon;

                iconHost.Click          += iconHost_Click;
                iconElement.ImageOpened += iconElement_ImageOpened;
                AdContainer.Children.Add(iconHost);

                try
                {
                    if (icon.Duration.HasValue)
                    {
#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
                        await TaskEx.Delay((int)icon.Duration.Value.TotalMilliseconds, cts.Token);
#else
                        await Task.Delay((int)icon.Duration.Value.TotalMilliseconds, cts.Token);
#endif
                    }
                    else
                    {
                        await cts.Token.AsTask();
                    }
                }
                catch (OperationCanceledException) { /* swallow */ }
                finally
                {
                    AdContainer.Children.Remove(iconHost);
                    iconHost.Click          -= iconHost_Click;
                    iconElement.ImageOpened -= iconElement_ImageOpened;
                }
            }
        }
Exemplo n.º 12
0
 public Result <StaticResource> AddStaticResource(StaticResource model)
 {
     return(base.Channel.AddStaticResource(model));
 }
Exemplo n.º 13
0
        //------------------消息处理-----------------
        private void ClientSocket_GetNewMessage_ChatForm(MessageModel Msg, System.Net.EndPoint From)
        {
            if (Msg.MessageType == MessageType.String)
            {
                MessageContent_String c = MessageModel.ToModel <MessageContent_String>(Msg.MessageContent);
                Msg.MessageContent = c;
                PrintMessageRouter();
            }
            else if (Msg.MessageType == MessageType.Get)
            {
                MessageContent_Get get = MessageModel.ToModel <MessageContent_Get>(Msg.MessageContent);
                if (get.RequestType == Get_Type.File)
                {
                    if (get.RequestFileType == File_Type.HeadImagoe)
                    {
                        IoTool.CreateDirectory(StaticResource.UserHeadImageBasePath);
                        String headPath = StaticResource.ToUserHeadImagePath(get.RequestArg + ".png");
                        IoTool.SaveFile(headPath, get.Content);
                        Dispatcher.Invoke(() =>
                        {
                            StaticResource.SetHeadImageSource(long.Parse(get.RequestArg.ToString()), ImageTool.GetUserHeadeImage(long.Parse(get.RequestArg.ToString())));
                        });
                    }
                }
            }
            else if (Msg.MessageType == MessageType.Login)
            {
                MessageContent_Login login = MessageModel.ToModel <MessageContent_Login>(Msg.MessageContent);
                if (login.LoginType == LoginType.OffOnLine)
                {
                    MessageBox.Show(MessageStringMark.GetCodeMsg(login.WithMessage));
                    Dispatcher.Invoke(() =>
                    {
                        OnCloseALL();
                    });
                }
            }
            else if (Msg.MessageType == MessageType.DataPacket)
            {
                MessageContent_DataPacket packet = MessageModel.ToModel <MessageContent_DataPacket>(Msg.MessageContent);
                //如果是图片的数据
                if (packet.PacketType == DataPacketType.ImageDataPacket)
                {
                    String fname = packet.FileName;
                    //如果是第一个包
                    if (packet.PacketIndex == 1)
                    {
                        DataPacketsFile.Add(fname, new WritingFile(StaticResource.MessageImagePath + fname)
                        {
                            Tag = packet.FileToken//这条实在没什么用
                        });
                    }
                    DataPacketsFile[fname].Writer(packet.Content);
                    if (packet.IsLastPacket)
                    {
                        DataPacketsFile[fname].WriterEnd();
                    }
                }
            }
            else if (Msg.MessageType == MessageType.Image)
            {
                MessageContent_Image img = MessageModel.ToModel <MessageContent_Image>(Msg.MessageContent);
                Msg.MessageContent = img;
                PrintMessageRouter();
            }
            else if (Msg.MessageType == MessageType.MakeFriend)
            {
                ChatHotContext DB = new ChatHotContext();

                MessageContent_MakeFriend content = MessageModel.ToModel <MessageContent_MakeFriend>(Msg.MessageContent);
                Msg.MessageContent = content;
                if (content.MakeFriendType == MakeFriendType.SendStart)
                {
                    if (MessageBox.Show("好友请求", "来自" + content, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                    {
                        //这个是返回消息所以是反着来的
                        //SocketTool.GetClientUDP().SendToServer(TheMessageModel.MAKEFRIEND(content.ToNum, content.FromNum, content.FromNum, content.ToNum, MakeFriendType.Success));
                        Msg.FromIpaddress      = StaticResource.IPV4Address.ToString();
                        Msg.FromLoginNumber    = content.ToNum;
                        Msg.ToLoginNumber      = content.FromNum;
                        content.MakeFriendType = MakeFriendType.Success;
                        Msg.MessageContent     = content;
                        SocketTool.GetClientUDP().SendToServer(Msg);
                        Dispatcher.Invoke(() =>
                        {
                            UserListForm.MainUserListForm.AddFriendsItem(DB.Users.Where(u => u.UloginNumber == content.FromNum).First());
                        });
                    }
                }
                else if (content.MakeFriendType == MakeFriendType.Success)
                {
                    MessageBox.Show("对方同意");
                    Dispatcher.Invoke(() =>
                    {
                        UserListForm.MainUserListForm.AddFriendsItem(DB.Users.Where(u => u.UloginNumber == content.ToNum).First());
                    });
                }
                else if (content.MakeFriendType == MakeFriendType.Fail)
                {
                    MessageBox.Show("对方拒绝");
                }
                else if (content.MakeFriendType == MakeFriendType.DeleteSuccess)
                {
                    Dispatcher.Invoke(() => {
                        UserListForm.MainUserListForm.RemoveFriendsItem(UserSource.UloginNumber == content.FromNum ? content.ToNum : content.FromNum);
                    });
                }
                DB.Dispose();
                return;
            }
            else if (Msg.MessageType == MessageType.UpdateUser)
            {
                MessageContent_UpdateUser content = MessageModel.ToModel <MessageContent_UpdateUser>(Msg.MessageContent);
                StaticResource.ALLUserSource = content.GetContent();
                Dispatcher.Invoke(() =>
                {
                    UserInfoChanged(content.GetContent());
                });
                //PrintMessageRouter(content);
            }
            //如果是需要提醒用户的消息就调用一下这个方法
            void PrintMessageRouter(Object content = null)
            {
                if (content != null)
                {
                    Msg.MessageContent = content;
                }
                //如果存在打开的对应登录号的聊天窗体
                if (MainChatForm != null && HasChatUser(Msg.FromLoginNumber))
                {
                    Dispatcher.Invoke(() =>
                    {
                        User UserFrom = GetUserByChatUsersItem(Msg.FromLoginNumber);
                        PrintMessage(Msg, UserFrom, UserSource);
                    });
                }
                //如果不存在
                else
                {
                    //MessageBox.Show("有新的消息--->>" + Msg.FromLoginNumber);
                    Dispatcher.Invoke(() =>
                    {
                        UserListForm.MainUserListForm.AppendToMessageQueue(Msg);
                    });
                }
            }
        }
Exemplo n.º 14
0
        private void importLocalization()
        {
            string xmlData = context.Request["xmlData"];

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xmlData);

            Provider.Database.Execute(() =>
            {
                HttpContext.Current.Cache.Remove("StaticResource");
                HttpContext.Current.Cache.Remove("StaticResourceLang");

                Provider.Database.Read <StaticResource>(1);
                Provider.Database.Read <StaticResourceLang>(1);

                Provider.Database.ExecuteNonQuery("truncate table StaticResourceLang;");
                Provider.Database.ExecuteNonQuery("truncate table StaticResource;");

                string[] defLangArr = Lang.GetLangFullCodeAndName(doc.FirstChild.Attributes["defaultLang"].Value);
                Lang def            = Provider.Database.Read <Lang>("Code={0}", defLangArr[0]);
                if (def == null)
                {
                    def = new Lang {
                        Name = defLangArr[1], Code = defLangArr[0]
                    };
                    def.Save();
                }

                Dictionary <string, Lang> langs = new Dictionary <string, Lang>();
                foreach (XmlNode node in doc.FirstChild.FirstChild.ChildNodes)
                {
                    string langCode  = node.Attributes["name"].Value;
                    string[] langArr = Lang.GetLangFullCodeAndName(langCode);
                    langs[langCode]  = Provider.Database.Read <Lang>("Code={0}", langArr[0]);
                    if (langs[langCode] == null)
                    {
                        langs[langCode] = new Lang {
                            Name = langArr[1], Code = langArr[0]
                        };
                        langs[langCode].Save();
                    }
                }

                foreach (XmlNode entry in doc.SelectNodes("/localization/entry"))
                {
                    var sr = new StaticResource {
                        Name = entry.Attributes["phrase"].Value
                    };
                    sr.Save();

                    foreach (XmlNode lang in entry.ChildNodes)
                    {
                        try
                        {
                            var srl = new StaticResourceLang {
                                Translation = lang.InnerText, StaticResourceId = sr.Id, LangId = langs[lang.Attributes["name"].Value].Id
                            };
                            srl.Save();
                        }
                        catch { }
                    }
                }
            });

            context.Response.Write("OK");
        }
Exemplo n.º 15
0
        private object GetStaticResourceKeyValue(StaticResource staticResource, IServiceProvider serviceProvider)
        { 
            System.Xaml.XamlReader reader = staticResource.ResourceNodeList.GetReader();
            XamlType xamlTypeStaticResourceExtension = reader.SchemaContext.GetXamlType(typeof(StaticResourceExtension));
            XamlMember xamlMemberResourceKey = xamlTypeStaticResourceExtension.GetMember("ResourceKey");
            reader.Read(); 
            if (reader.NodeType == Xaml.XamlNodeType.StartObject && reader.Type == xamlTypeStaticResourceExtension)
            { 
                reader.Read(); 
                // Skip Members that aren't _PositionalParameters or ResourceKey
                while (reader.NodeType == Xaml.XamlNodeType.StartMember && 
                    (reader.Member != XamlLanguage.PositionalParameters && reader.Member != xamlMemberResourceKey))
                {
                    reader.Skip();
                } 

                // Process the Member Value of _PositionParameters or ResourceKey 
                if (reader.NodeType == Xaml.XamlNodeType.StartMember) 
                {
                    object value = null; 
                    reader.Read();
                    if (reader.NodeType == Xaml.XamlNodeType.StartObject)
                    {
                        System.Xaml.XamlReader subReader = reader.ReadSubtree(); 

                        value = EvaluateMarkupExtensionNodeList(subReader, serviceProvider); 
                    } 
                    else if (reader.NodeType == Xaml.XamlNodeType.Value)
                    { 
                        value = reader.Value;
                    }
                    return value;
                } 
            }
            return null; 
        } 
Exemplo n.º 16
0
 /// <summary>
 /// 手动更改用户信息
 /// </summary>
 public static void UserInfoChanged(User NewUser)
 {
     UserListForm.MainUserListForm.UserSource = NewUser;
     StaticResource.SetHeadImageSource(NewUser.UloginNumber ?? 0, ImageTool.GetUserHeadeImage(NewUser.UloginNumber ?? 0));
     ImageTool.GetUserHeadImage(NewUser.UloginNumber ?? 0);
 }
Exemplo n.º 17
0
        /// <summary>
        /// 上传静态文件
        /// </summary>
        /// <returns></returns>
        public JsonResult UploadResource()
        {
            string app = Request["app"] ?? "epm";
            // 是否生成压缩图片
            string crop      = Request["crop"];
            bool   cropValue = "true".Equals((string.IsNullOrWhiteSpace(crop) ? "false" : crop).ToLower());

            try
            {
                foreach (string file in Request.Files)
                {
                    if (!string.IsNullOrEmpty(file))
                    {
                        using (ClientProxyFileServer proxy = new ClientProxyFileServer(ProxyEx(Request)))
                        {
                            HttpPostedFileBase postedFile    = Request.Files[file];                    //获取客户端上载文件的集合
                            string             extensionName = Path.GetExtension(postedFile.FileName); //获取客户端上传文件的名称

                            //获取文件存储目录
                            var configList = proxy.GetConfig(app);
                            var config     = configList.Data.FirstOrDefault(i => i.FileTypeName == "static" && i.FileTypeExtension.Contains(extensionName));
                            if (config == null)
                            {
                                return(Json(new { flag = false, result = "不允许上传此类型的文件" }));
                            }

                            var    pathList = CreatePath(config);
                            string filePath = pathList[1];
                            string reName   = Guid.NewGuid().ToString() + extensionName;
                            string fullPath = filePath + "\\" + reName;
                            postedFile.SaveAs(fullPath); //保存文件内容


                            FileInfo fileInfo = new FileInfo(fullPath);
                            //正式文件入库
                            StaticResource sr = new StaticResource();
                            sr.App        = app;
                            sr.Extension  = extensionName;
                            sr.FilePath   = fullPath;
                            sr.FileSize   = fileInfo.Length;
                            sr.Guid       = Guid.NewGuid().ToString();
                            sr.UploadTime = DateTime.Now;
                            sr.HttpURL    = "";
                            sr.Name       = postedFile.FileName;
                            sr.VirtualURL = (filePath.Replace(config.ParentPath, "/").Replace("\\", "/") + "/" + reName);
                            sr            = proxy.AddStaticResource(sr).Data;

                            List <StaticResource> list = new List <StaticResource>();

                            list.Add(sr);

                            if (ImageHelper.IsImage(extensionName) && cropValue)
                            {
                                string bigReName           = Guid.NewGuid() + extensionName;
                                string bigCropmageFilePath = filePath + "\\" + bigReName;

                                string smallReName           = Guid.NewGuid() + postedFile.FileName;
                                string smallCropmageFilePath = filePath + "\\" + smallReName;

                                ImageHelper.CompressImage(fullPath, bigCropmageFilePath);

                                // TODO: 此处指定压缩大小可改为系统配置项
                                ImageHelper.MakeThumbnailImage(fullPath, smallCropmageFilePath, 300, 300, ImageHelper.ImageCutMode.Cut);

                                StaticResource files = CreateStaticResource(bigCropmageFilePath, app, extensionName, "epmbig" + postedFile.FileName, bigReName, filePath, config);
                                files = proxy.AddStaticResource(files).Data;
                                list.Add(files);

                                StaticResource smallFiles = CreateStaticResource(smallCropmageFilePath, app, extensionName, "epmsmall" + postedFile.FileName, smallReName, filePath, config);
                                smallFiles = proxy.AddStaticResource(smallFiles).Data;
                                list.Add(smallFiles);
                            }

                            //return Json(new { flag = true, type = "static", file = sr }, JsonRequestBehavior.AllowGet);
                            return(Json(new { flag = true, type = "static", file = list }, JsonRequestBehavior.AllowGet));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(Json(new { flag = false, result = ex.Message }, JsonRequestBehavior.AllowGet));
            }
            return(Json(new { flag = false, result = "文件上传失败" }, JsonRequestBehavior.AllowGet));
        }
        /// <inheritdoc /> 
        protected virtual async void ShowIcon(Microsoft.Media.Advertising.Icon icon, StaticResource staticResource, CancellationTokenSource cts)
        {
            if (icon.Offset.HasValue)
            {
                try
                {
#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
                    await TaskEx.Delay((int)icon.Offset.Value.TotalMilliseconds, cts.Token);
#else
                    await Task.Delay((int)icon.Offset.Value.TotalMilliseconds, cts.Token);
#endif
                }
                catch (OperationCanceledException) { /* swallow */ }
            }

            if (!cts.IsCancellationRequested)
            {
                var iconHost = new HyperlinkButton();
                iconHost.NavigateUri = icon.ClickThrough;

                double topMargin = 0;
                double leftMargin = 0;
                if (icon.Width.HasValue)
                {
                    iconHost.Width = icon.Width.Value;
                }
                if (icon.Height.HasValue)
                {
                    iconHost.Height = icon.Height.Value;
                }
                switch (icon.XPosition)
                {
                    case "left":
                        iconHost.HorizontalAlignment = HorizontalAlignment.Left;
                        break;
                    case "right":
                        iconHost.HorizontalAlignment = HorizontalAlignment.Right;
                        break;
                    default:
                        iconHost.HorizontalAlignment = HorizontalAlignment.Left;
                        int xPositionValue;
                        if (int.TryParse(icon.XPosition, out xPositionValue))
                        {
                            leftMargin = xPositionValue;
                        }
                        break;
                }
                switch (icon.YPosition)
                {
                    case "top":
                        iconHost.VerticalAlignment = VerticalAlignment.Top;
                        break;
                    case "bottom":
                        iconHost.VerticalAlignment = VerticalAlignment.Bottom;
                        break;
                    default:
                        iconHost.VerticalAlignment = VerticalAlignment.Top;
                        int yPositionValue;
                        if (int.TryParse(icon.YPosition, out yPositionValue))
                        {
                            topMargin = yPositionValue;
                        }
                        break;
                }
                iconHost.Margin = new Thickness(leftMargin, topMargin, 0, 0);

                var iconElement = new Image();
                iconElement.Stretch = Stretch.Fill;
                iconElement.Source = new BitmapImage(staticResource.Value);
                iconHost.Content = iconElement;

                //TODO: avoid visually overlaping icons

                iconHost.Tag = icon;
                iconElement.Tag = icon;

                iconHost.Click += iconHost_Click;
                iconElement.ImageOpened += iconElement_ImageOpened;
                AdContainer.Children.Add(iconHost);

                try
                {
                    if (icon.Duration.HasValue)
                    {
#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
                        await TaskEx.Delay((int)icon.Duration.Value.TotalMilliseconds, cts.Token);
#else
                        await Task.Delay((int)icon.Duration.Value.TotalMilliseconds, cts.Token);
#endif
                    }
                    else
                    {
                        await cts.Token.AsTask();
                    }
                }
                catch (OperationCanceledException) { /* swallow */ }
                finally
                {
                    AdContainer.Children.Remove(iconHost);
                    iconHost.Click -= iconHost_Click;
                    iconElement.ImageOpened -= iconElement_ImageOpened;
                }
            }
        }