Пример #1
0
 internal DataTable IsBookAlreadyIssuedToReader(BJBookInfo book, ReaderInfo reader)
 {
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
         SqlDataAdapter dataAdapter = new SqlDataAdapter(Queries.IS_BOOK_ALREADY_ISSUED_TO_READER, connection);
         dataAdapter.SelectCommand.Parameters.Add("IDReader", SqlDbType.Int).Value    = reader.NumberReader;
         dataAdapter.SelectCommand.Parameters.Add("BookID", SqlDbType.NVarChar).Value = book.Id;
         DataTable table = new DataTable();
         int       cnt   = dataAdapter.Fill(table);
         return(table);
     }
 }
 /// <summary>
 /// 续时
 /// </summary>
 /// <param name="cardNo"></param>
 /// <returns></returns>
 public string DelaySeatUsedTime(ReaderInfo reader)
 {
     try
     {
         string str = seatManage.DelaySeatUsedTime(reader);
         return(str);
     }
     catch (Exception ex)
     {
         throw new ReaderHandlerFailed(ex.Message);
     }
 }
 /// <summary>
 /// 获取读者信息
 /// </summary>
 /// <param name="cardNo"></param>
 /// <returns></returns>
 public SeatManage.ClassModel.ReaderInfo GetReaderInfo(string cardNo)
 {
     try
     {
         ReaderInfo reader = seatManage.GetReader(cardNo, true);
         return(reader);
     }
     catch (Exception ex)
     {
         throw new ReaderHandlerFailed(string.Format("获取读者{0}的信息时遇到异常:{1}", cardNo, ex.Message));
     }
 }
Пример #4
0
 /// <summary>
 /// 验证读者类型
 /// </summary>
 /// <param name="reader"></param>
 /// <param name="roomSet"></param>
 /// <returns></returns>
 public static bool ProvenReaderType(ReaderInfo reader, ReadingRoomSetting roomSet)
 {
     if (!roomSet.LimitReaderEnter.Used)
     {
         return(true);
     }
     string[] readerTypes = roomSet.LimitReaderEnter.ReaderTypes.Split(';');
     if (readerTypes.Any(t => reader.ReaderType == t))
     {
         return(roomSet.LimitReaderEnter.CanEnter);
     }
     return(!roomSet.LimitReaderEnter.CanEnter);
 }
Пример #5
0
        private void button2_Click(object sender, EventArgs e)
        {
            //f1.FrmlrFam(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("Читатель не выбран!");
                return;
            }
            ReaderInfo reader = ReaderInfo.GetReader((int)dataGridView1.SelectedRows[0].Cells[0].Value);

            f1.FillFormular(reader);
            Close();
        }
Пример #6
0
        public override void DataBind()
        {
            ReaderInfo reader = handler.GetReaderInfo(LoginUserInfo.CardNo);

            if (!reader.PecketWebSetting.UseBookSeat)
            {
                btn_book.Visible = false;
            }
            if (!reader.PecketWebSetting.UseWaitSeat)
            {
                btn_WaitSeat.Visible = false;
            }
        }
Пример #7
0
        internal DataTable IsTwentyFourHoursPastSinceReturn(ReaderInfo reader, BJBookInfo book)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlDataAdapter dataAdapter = new SqlDataAdapter(Queries.IS_TWENTYFOUR_HOURS_PAST_SINCE_RETURN, connection);
                dataAdapter.SelectCommand.Parameters.Add("BookId", SqlDbType.NVarChar).Value = book.Id;
                dataAdapter.SelectCommand.Parameters.Add("ReaderId", SqlDbType.Int).Value    = reader.NumberReader;

                DataTable table = new DataTable();
                int       cnt   = dataAdapter.Fill(table);
                return(table);
            }
        }
Пример #8
0
        public static ReaderSimpleView GetReaderSimpleView(ReaderInfo reader)
        {
            ReaderSimpleView result = new ReaderSimpleView();

            result.FamilyName       = reader.FamilyName;
            result.Name             = reader.Name;
            result.FatherName       = reader.FatherName;
            result.ReaderId         = reader.NumberReader;
            result.MobilePhone      = reader.MobileTelephone;
            result.Email            = reader.Email;
            result.IsRemoteReader   = reader.IsRemoteReader;
            result.IsPasswordExists = !string.IsNullOrEmpty(reader.HashedPassword);
            return(result);
        }
Пример #9
0
        public HttpResponseMessage CountriesList()
        {
            Dictionary <int, string> Countries;

            try
            {
                Countries = ReaderInfo.GetCountriesList();
            }
            catch (Exception ex)
            {
                return(ALISErrorFactory.CreateError(ex.Message, Request));
            }
            return(ALISResponseFactory.CreateResponse(Countries, Request));
        }
Пример #10
0
        public void IssueElectronicCopyToReader(int IDREADER)
        {
            ReaderInfo        reader = ReaderInfo.GetReader(IDREADER);
            BJDatabaseWrapper dbw    = new BJDatabaseWrapper(this.Fund);

            byte[] random = new byte[20];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            rng.GetBytes(random); // The array is now filled with cryptographically strong random bytes.
            string ViewKey         = Convert.ToBase64String(random);
            int    IssuePeriodDays = 30;

            dbw.IssueElectronicCopyToReader(this.ID, IssuePeriodDays, ViewKey, IDREADER, reader.TypeReader);
        }
Пример #11
0
        /// <summary>
        /// 座位暂离
        /// </summary>
        /// <param name="cardNo"></param>
        /// <returns></returns>
        public string SeatShortLeave(string cardNo, string clientNo, string remark)
        {
            ReaderInfo reader = null;

            try
            {
                reader = GetReader(cardNo, true);
            }
            catch (Exception ex)
            {
                throw new Exception("获取读者状态遇到异常");
            }
            if (reader != null)
            {
                if (reader.EnterOutLog == null)
                {
                    throw new Exception("暂离失败,您还没有选座。");
                }
                switch (reader.EnterOutLog.EnterOutState)
                {
                case EnterOutLogType.BookingConfirmation: //预约入座
                case EnterOutLogType.SelectSeat:          //选座
                case EnterOutLogType.ContinuedTime:       //续时
                case EnterOutLogType.ComeBack:            //暂离回来
                case EnterOutLogType.ReselectSeat:        //重新选座
                case EnterOutLogType.WaitingSuccess:      //等待入座
                    reader.EnterOutLog.EnterOutState = EnterOutLogType.ShortLeave;
                    double shortTimeMin = GetSeatHoldTime(reader.AtReadingRoom.Setting.SeatHoldTime, DateTime.Now);
                    string rem          = ",设置" + reader.EnterOutLog.ReadingRoomName + "第" + reader.EnterOutLog.ShortSeatNo + "号座位暂离,座位保留" + shortTimeMin + "分钟";
                    reader.EnterOutLog.Remark       = remark + rem;
                    reader.EnterOutLog.Flag         = Operation.Reader;
                    reader.EnterOutLog.EnterOutTime = DateTime.Now;
                    reader.EnterOutLog.TerminalNum  = clientNo;
                    return(ShortLeave(reader));

                case EnterOutLogType.ShortLeave:
                    throw new Exception("暂离失败,您已经是暂离状态。");

                case EnterOutLogType.Leave:
                    throw new Exception("暂离失败,您还没有入座。");

                default:
                    throw new Exception("暂离失败,您当前不是在座状态");
                }
            }
            else
            {
                throw new Exception("执行遇到错误");
            }
        }
Пример #12
0
        /// <summary>
        /// Format reader.
        /// </summary>
        public static string FormatReader
        (
            [NotNull] ReaderInfo reader
        )
        {
            Code.NotNull(reader, "reader");

            using (IrbisConnection connection = GetIrbisConnection())
            {
                string result = connection.FormatRecord("@", reader.Mfn);

                return(result);
            }
        }
        /// <summary>
        /// 发送微信信息
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="message"></param>
        public static void SendWeiXinMessage(ReaderInfo reader, string message)
        {
            IWCFService.ISeatManageService seatService = new WcfServiceForSeatManage.SeatManageDateService();
            bool error = false;

            try
            {
                seatService.SendWeiXinMessage(reader, message);
            }
            catch (Exception ex)
            {
                SeatManageComm.WriteLog.Write("发送微信信息失败:" + ex.Message);
            }
        }
Пример #14
0
        static void ProcessReader
        (
            ReaderInfo reader
        )
        {
            DateTime         registration = reader.RegistrationDate;
            DateTime         threshold    = registration.AddYears(1);
            List <VisitInfo> visits       = reader.Visits
                                            .Where(v => v.IsVisit && v.DateGiven < threshold)
                                            .Distinct(new ByDate())
                                            //.Where(v => !v.Department.SameString("АБ"))
                                            .ToList();

            reader.Visits = visits.ToArray();
        }
Пример #15
0
        public static void DeleteCard
        (
            [NotNull] ReaderInfo reader
        )
        {
            Code.NotNull(reader, "reader");

            string ticket = reader.Ticket.ThrowIfNull();

            Client.DeleteCard
            (
                ticket,
                true
            );
        }
Пример #16
0
        public static JObject BuildCard
        (
            [NotNull] ReaderInfo reader
        )
        {
            Code.NotNull(reader, "reader");

            JObject result = OsmiUtility.BuildCardForReader
                             (
                Template,
                reader
                             );

            return(result);
        }
Пример #17
0
        internal DataTable IsElectronicIssueAlreadyIssued(ReaderInfo reader, BJBookInfo book)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlDataAdapter dataAdapter = new SqlDataAdapter(Queries.IS_ELECTRONIC_ISSUE_ALREADY_ISSUED, connection);
                dataAdapter.SelectCommand.Parameters.Add("IDReader", SqlDbType.Int).Value    = reader.NumberReader;
                dataAdapter.SelectCommand.Parameters.Add("BookId", SqlDbType.NVarChar).Value = book.Id;
                dataAdapter.SelectCommand.Parameters.Add("BookIdInt", SqlDbType.Int).Value   = book.ID;
                dataAdapter.SelectCommand.Parameters.Add("BASE", SqlDbType.Int).Value        = (book.Fund == "BJVVV")? 1 : 2;

                DataTable table = new DataTable();
                int       cnt   = dataAdapter.Fill(table);
                return(table);
            }
        }
Пример #18
0
        public static ReaderInfo GetReader
        (
            [NotNull] string ticket
        )
        {
            Code.NotNullNorEmpty(ticket, "ticket");

            using (IrbisConnection connection = GetIrbisConnection())
            {
                ReaderManager manager = new ReaderManager(connection);
                ReaderInfo    result  = manager.GetReader(ticket);

                return(result);
            }
        }
Пример #19
0
 public string DelaySeatUsedTime(ReaderInfo reader)
 {
     try
     {
         lock (this.client)
         {
             client.Connect();
             request            = new SocketRequest();
             request.MethodName = "DelaySeatUsedTime";
             request.Parameters.Add(reader);
             request.SubSystem = TcpSeatManageSubSystem.WeiXinSeatBespeak;
             request.Target    = schoolNum;
             request.MsgType   = TcpMsgDataType.Relay;
             if (request != null)
             {
                 client.Send(SeatManage.SeatManageComm.ByteSerializer.ObjectToByte(request));
                 Console.WriteLine("请求客户端{0}执行{1}方法已发送,等待返回结果…", request.Target, request.MethodName);
             }
             autoConnectEvent.WaitOne(20000);
             if (response == null)
             {
                 throw new Exception("连接超时。");
             }
             else if (!isError && response.MethodName.Equals("DelaySeatUsedTime") && string.IsNullOrEmpty(response.ErrorMsg))
             {
                 return(response.Result.ToString());
             }
             else if (!string.IsNullOrEmpty(response.ErrorMsg))
             {
                 throw new Exception(response.ErrorMsg);
             }
             else
             {
                 return(null);
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         client.Disconnect();
         request  = null;
         response = null;
     }
 }
Пример #20
0
        public HttpResponseMessage Get(int ReaderId)
        {
            ReaderInfo reader;

            try
            {
                reader = ReaderInfo.GetReader(ReaderId);
            }
            catch (Exception ex)
            {
                return(ALISErrorFactory.CreateError(ex.Message, Request));
            }
            ReaderSimpleView result = ReaderViewFactory.GetReaderSimpleView(reader);

            return(ALISResponseFactory.CreateResponse(result, Request));
        }
Пример #21
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            try
            {
                this.getIniFile();
                mReader     = new clsReader();
                mReaderInfo = mReader.ReaderSettings;

                this.Text = "Alien阅读器";
                Thread.CurrentThread.Name = "TestTagList";
                btnTagList.Enabled        = false;
                btnParse.Enabled          = false;
                btnSent.Enabled           = false;
            }
            catch {}
        }
Пример #22
0
        private void ParseAndAddReader
        (
            MarcRecord record
        )
        {
            ReaderInfo reader = ReaderInfo.Parse(record);
            string     status = reader.Status;

            if (string.IsNullOrEmpty(status))
            {
                reader.Status = "0";
                status        = "0";
            }
            Readers.Add(reader);
            ReadersByStatus.Add(status, reader);
        }
Пример #23
0
        internal BARType CheckBAR(string data)
        {
            BJBookInfo book = BJBookInfo.GetBookInfoByBAR(data);

            if (book != null)
            {
                return(BARType.Book);
            }
            ReaderInfo reader = ReaderInfo.GetReaderByBar(data);

            if (reader != null)
            {
                return(BARType.Reader);
            }
            return(BARType.NotExist);
        }
        /// <summary>
        /// 设置暂离,返回操作结果。
        /// </summary>
        /// <param name="school">学校</param>
        /// <param name="reader">读者</param>
        /// <returns></returns>
        public string SetShortLeave(string cardNo)
        {
            ReaderInfo reader = null;

            try
            {
                reader = seatManage.GetReader(cardNo, true);
            }
            catch (Exception ex)
            {
                throw new Exception("获取读者状态遇到异常");
            }
            if (reader != null)
            {
                if (reader.EnterOutLog == null)
                {
                    throw new Exception("暂离失败,您还没有选座。");
                }
                switch (reader.EnterOutLog.EnterOutState)
                {
                case EnterOutLogType.BookingConfirmation: //预约入座
                case EnterOutLogType.SelectSeat:          //选座
                case EnterOutLogType.ContinuedTime:       //续时
                case EnterOutLogType.ComeBack:            //暂离回来
                case EnterOutLogType.ReselectSeat:        //重新选座
                case EnterOutLogType.WaitingSuccess:      //等待入座
                    reader.EnterOutLog.EnterOutState = EnterOutLogType.ShortLeave;
                    reader.EnterOutLog.Remark        = "读者通过手机客户端设置暂时离开。";
                    reader.EnterOutLog.Flag          = Operation.Reader;
                    reader.EnterOutLog.EnterOutTime  = DateTime.Now;
                    return(ShortLeave(reader));

                case EnterOutLogType.ShortLeave:
                    throw new Exception("暂离失败,您已经是暂离状态。");

                case EnterOutLogType.Leave:
                    throw new Exception("暂离失败,您还没有入座。");

                default:
                    throw new Exception("暂离失败,您当前不是在座状态");
                }
            }
            else
            {
                throw new Exception("执行遇到错误");
            }
        }
Пример #25
0
        internal bool IsTwentyFourHoursPastSinceReturn(ReaderInfo reader, BJBookInfo book)
        {
            DataTable table = dbWrapper.IsTwentyFourHoursPastSinceReturn(reader, book);

            if (table.Rows.Count == 0)
            {
                return(true);
            }
            if ((DateTime.Now - (DateTime)table.Rows[0]["Changed"]).Days < 1)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Пример #26
0
        /// <summary>
        ///     修改读者信息
        /// </summary>
        /// <param name="mod"></param>
        /// <exception cref="MySqlException">更新失败</exception>
        /// <exception cref="Exception">输入错误</exception>
        public void ReaderModifyInfo(ReaderInfoModel mod)
        {
            try
            {
                GlobalFunc.InfoCheck(mod, mod.Contact != null);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (mod.ID < 10000)
            {
                throw new Exception("Permission Denied");
            }

            ReaderInfoModel tmpDic;

            try
            {
                tmpDic = GetReaderInfo(mod.ID);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            tmpDic.UpdateInfo(mod);
            var newInfo = new ReaderInfo().UpdateInfo(tmpDic);

            try
            {
                DbContext.DBstatic.Updateable(newInfo).IgnoreColumns(true, ignoreAllDefaultValue: true)
                .ExecuteCommand();
            }
            catch (MySqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #27
0
        public static void SendSms
        (
            [NotNull] ReaderInfo reader
        )
        {
            Code.NotNull(reader, "reader");

            string ticket      = reader.Ticket.ThrowIfNull();
            string phoneNumber = reader.HomePhone.ThrowIfNull();

            Client.SendCardSms
            (
                ticket,
                phoneNumber
            );

            WriteLine("Послано сообщение на номер {0}", phoneNumber);
        }
Пример #28
0
 internal void AttendanceScan(string barcode, BJUserInfo bjUser)
 {
     if (ReaderInfo.IsRightReaderBarcode(barcode))
     {
         if (this.IsAlreadyVisitedToday(barcode, bjUser))
         {
             throw new Exception("C024");
         }
         else
         {
             loader.AddAttendance(barcode, bjUser);
         }
     }
     else
     {
         throw new Exception("C023");
     }
 }
Пример #29
0
        public static string DelaySeatUsedTime(ReaderInfo model)
        {
            IWCFService.ISeatManageService seatService = new WcfServiceForSeatManage.SeatManageDateService();
            bool   error  = false;
            string result = "";

            try
            {
                result = seatService.DelaySeatUsedTime(model);
                return(result);
            }
            catch (Exception ex)
            {
                error = true;
                WriteLog.Write("延长座位使用时间遇到错误:" + ex.Message);
                return(result);
            }
        }
Пример #30
0
        public static void SendEmail
        (
            [NotNull] ReaderInfo reader
        )
        {
            Code.NotNull(reader, "reader");

            string ticket = reader.Ticket.ThrowIfNull();
            string email  = reader.Email.ThrowIfNull();

            Client.SendCardMail
            (
                ticket,
                email
            );

            WriteLine("Послано письмо по адресу {0}", email);
        }
Пример #31
0
        /// <summary>
        /// Reads resources from an assembly.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="outFileOrDir"> Output file or directory. </param>
        /// <remarks> This should not run for Framework assemblies. </remarks>
        internal void ReadAssemblyResources(String name, String outFileOrDir)
        {
            // If something else in the solution failed to build...
            if (!File.Exists(name))
            {
                _logger.LogErrorWithCodeFromResources("GenerateResource.MissingFile", name);
                return;
            }

            Assembly a = null;
            bool mainAssembly = false;
            bool failedLoadingCultureInfo = false;
            NeutralResourcesLanguageAttribute neutralResourcesLanguageAttribute = null;
            AssemblyName assemblyName = null;

            try
            {
                a = Assembly.UnsafeLoadFrom(name);
                assemblyName = a.GetName();

                if (_extractResWFiles)
                {
                    var targetFrameworkAttribute = a.GetCustomAttribute<TargetFrameworkAttribute>();
                    if (
                            targetFrameworkAttribute != null &&
                            (
                                targetFrameworkAttribute.FrameworkName.StartsWith("Silverlight,", StringComparison.OrdinalIgnoreCase) ||
                                targetFrameworkAttribute.FrameworkName.StartsWith("WindowsPhone,", StringComparison.OrdinalIgnoreCase)
                            )
                        )
                    {
                        // Skip Silverlight assemblies.
                        _logger.LogMessageFromResources("GenerateResource.SkippingExtractingFromNonSupportedFramework", name, targetFrameworkAttribute.FrameworkName);
                        return;
                    }

                    _logger.LogMessageFromResources("GenerateResource.ExtractingResWFiles", name, outFileOrDir);
                }

                CultureInfo ci = null;
                try
                {
                    ci = assemblyName.CultureInfo;
                }
                catch (ArgumentException e)
                {
                    _logger.LogWarningWithCodeFromResources(null, name, 0, 0, 0, 0, "GenerateResource.CreatingCultureInfoFailed", e.GetType().Name, e.Message, assemblyName.ToString());
                    failedLoadingCultureInfo = true;
                }

                if (!failedLoadingCultureInfo)
                {
                    mainAssembly = ci.Equals(CultureInfo.InvariantCulture);
                    neutralResourcesLanguageAttribute = CheckAssemblyCultureInfo(name, assemblyName, ci, a, mainAssembly);
                }  // if (!failedLoadingCultureInfo)
            }
            catch (BadImageFormatException)
            {
                // If we're extracting ResW files, this task is being run on all DLL's referred to by the project.
                // That may potentially include C++ libraries & immersive (non-portable) class libraries, which don't have resources.
                // We can't easily filter those.  We can simply skip them.
                return;
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                    throw;
                _logger.LogErrorWithCodeFromResources("GenerateResource.CannotLoadAssemblyLoadFromFailed", name, e);
            }

            if (a != null)
            {
                String[] resources = a.GetManifestResourceNames();
                CultureInfo satCulture = null;
                String expectedExt = null;
                if (!failedLoadingCultureInfo)
                {
                    satCulture = assemblyName.CultureInfo;
                    if (!satCulture.Equals(CultureInfo.InvariantCulture))
                        expectedExt = '.' + satCulture.Name + ".resources";
                }

                foreach (String resName in resources)
                {
                    if (!resName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) // Skip non-.resources assembly blobs
                        continue;

                    if (mainAssembly)
                    {
                        if (CultureInfo.InvariantCulture.CompareInfo.IsSuffix(resName, ".en-US.resources", CompareOptions.IgnoreCase))
                        {
                            _logger.LogErrorFromResources("GenerateResource.ImproperlyBuiltMainAssembly", resName, name);
                            continue;
                        }

                        if (neutralResourcesLanguageAttribute == null)
                        {
                            _logger.LogWarningWithCodeFromResources(null, name, 0, 0, 0, 0, "GenerateResource.MainAssemblyMissingNeutralResourcesLanguage", name);
                            break;
                        }
                    }
                    else if (!failedLoadingCultureInfo && !CultureInfo.InvariantCulture.CompareInfo.IsSuffix(resName, expectedExt, CompareOptions.IgnoreCase))
                    {
                        _logger.LogErrorFromResources("GenerateResource.ImproperlyBuiltSatelliteAssembly", resName, expectedExt, name);
                        continue;
                    }

                    try
                    {
                        Stream s = a.GetManifestResourceStream(resName);
                        using (IResourceReader rr = new ResourceReader(s))
                        {
                            ReaderInfo reader = new ReaderInfo();
                            if (mainAssembly)
                            {
                                reader.fromNeutralResources = true;
                                reader.assemblySimpleName = assemblyName.Name;
                            }
                            else
                            {
                                Debug.Assert(assemblyName.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase));
                                reader.assemblySimpleName = assemblyName.Name.Remove(assemblyName.Name.Length - 10);  // Remove .resources from satellite assembly name
                            }
                            reader.outputFileName = resName.Remove(resName.Length - 10); // Remove the .resources extension
                            if (satCulture != null && !String.IsNullOrEmpty(satCulture.Name))
                            {
                                reader.cultureName = satCulture.Name;
                            }
                            else if (neutralResourcesLanguageAttribute != null && !String.IsNullOrEmpty(neutralResourcesLanguageAttribute.CultureName))
                            {
                                reader.cultureName = neutralResourcesLanguageAttribute.CultureName;
                            }

                            if (reader.cultureName != null)
                            {
                                // Remove the culture from the filename
                                if (reader.outputFileName.EndsWith("." + reader.cultureName, StringComparison.OrdinalIgnoreCase))
                                    reader.outputFileName = reader.outputFileName.Remove(reader.outputFileName.Length - (reader.cultureName.Length + 1));
                            }
                            _readers.Add(reader);

                            foreach (DictionaryEntry pair in rr)
                            {
                                AddResource(reader, (string)pair.Key, pair.Value, resName);
                            }
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        _logger.LogErrorWithCodeFromResources(null, name, 0, 0, 0, 0, "GenerateResource.NoResourcesFileInAssembly", resName);
                    }
                }
            }

            var satelliteAssemblies = _satelliteInFiles.Where(ti => ti.GetMetadata("OriginalItemSpec").Equals(name, StringComparison.OrdinalIgnoreCase));

            foreach (var satelliteAssembly in satelliteAssemblies)
            {
                ReadAssemblyResources(satelliteAssembly.ItemSpec, outFileOrDir);
            }
        }
Пример #32
0
 /// <summary>
 /// Add a resource from an XML or binary format file to the internal data structures
 /// </summary>
 /// <param name="name">Resource name</param>
 /// <param name="value">Resource value</param>
 /// <param name="inputFileName">Input file for messages</param>
 private void AddResource(ReaderInfo reader, string name, object value, String inputFileName)
 {
     AddResource(reader, name, value, inputFileName, 0, 0);
 }
Пример #33
0
        /// <summary>
        /// Add a resource from a text file to the internal data structures
        /// </summary>
        /// <param name="name">Resource name</param>
        /// <param name="value">Resource value</param>
        /// <param name="inputFileName">Input file for messages</param>
        /// <param name="lineNumber">Line number for messages</param>
        /// <param name="linePosition">Column number for messages</param>
        private void AddResource(ReaderInfo reader, string name, object value, String inputFileName, int lineNumber, int linePosition)
        {
            Entry entry = new Entry(name, value);

            if (reader.resourcesHashTable.ContainsKey(name))
            {
                _logger.LogWarningWithCodeFromResources(null, inputFileName, lineNumber, linePosition, 0, 0, "GenerateResource.DuplicateResourceName", name);
                return;
            }

            reader.resources.Add(entry);
            reader.resourcesHashTable.Add(name, value);
        }
Пример #34
0
        /// <summary>
        /// Write resources to a text format resources file
        /// </summary>
        /// <param name="fileName">Output resources file</param>
        private void WriteTextResources(ReaderInfo reader, String fileName)
        {
            using (StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8))
            {
                foreach (Entry entry in reader.resources)
                {
                    String key = entry.name;
                    Object v = entry.value;
                    String value = v as String;
                    if (value == null)
                    {
                        _logger.LogErrorWithCodeFromResources(null, fileName, 0, 0, 0, 0, "GenerateResource.OnlyStringsSupported", key, v.GetType().FullName);
                    }
                    else
                    {
                        // Escape any special characters in the String.
                        value = value.Replace("\\", "\\\\");
                        value = value.Replace("\n", "\\n");
                        value = value.Replace("\r", "\\r");
                        value = value.Replace("\t", "\\t");

                        writer.WriteLine("{0}={1}", key, value);
                    }
                }
            }
        }
Пример #35
0
 /// <summary>
 /// Write resources to an XML or binary format resources file.
 /// </summary>
 /// <remarks>Closes writer automatically</remarks>
 /// <param name="writer">Appropriate IResourceWriter</param>
 private void WriteResources(ReaderInfo reader, IResourceWriter writer)
 {
     Exception capturedException = null;
     try
     {
         foreach (Entry entry in reader.resources)
         {
             string key = entry.name;
             object value = entry.value;
             writer.AddResource(key, value);
         }
     }
     catch (Exception e)
     {
         capturedException = e; // Rethrow this after catching exceptions thrown by Close().
     }
     finally
     {
         if (capturedException == null)
         {
             writer.Close(); // If this throws, exceptions will be caught upstream.
         }
         else
         {
             // It doesn't hurt to call Close() twice. In the event of a full disk, we *need* to call Close() twice.
             // In that case, the first time we catch an exception indicating that the XML written to disk is malformed,
             // specifically an InvalidOperationException: "Token EndElement in state Error would result in an invalid XML document."
             try { writer.Close(); }
             catch (Exception) { } // We agressively catch all exception types since we already have one we will throw.
             // The second time we catch the out of disk space exception.
             try { writer.Close(); }
             catch (Exception) { } // We agressively catch all exception types since we already have one we will throw.
             throw capturedException; // In the event of a full disk, this is an out of disk space IOException.
         }
     }
 }
Пример #36
0
        /// <summary>
        /// Read resources from a text format file
        /// </summary>
        /// <param name="fileName">Input resources filename</param>
        private void ReadTextResources(ReaderInfo reader, String fileName)
        {
            // Check for byte order marks in the beginning of the input file, but
            // default to UTF-8.
            using (LineNumberStreamReader sr = new LineNumberStreamReader(fileName, new UTF8Encoding(true), true))
            {
                StringBuilder name = new StringBuilder(255);
                StringBuilder value = new StringBuilder(2048);

                int ch = sr.Read();
                while (ch != -1)
                {
                    if (ch == '\n' || ch == '\r')
                    {
                        ch = sr.Read();
                        continue;
                    }

                    // Skip over commented lines or ones starting with whitespace.
                    // Support LocStudio INF format's comment char, ';'
                    if (ch == '#' || ch == '\t' || ch == ' ' || ch == ';')
                    {
                        // comment char (or blank line) - skip line.
                        sr.ReadLine();
                        ch = sr.Read();
                        continue;
                    }
                    // Note that in Beta of version 1 we recommended users should put a [strings] 
                    // section in their file.  Now it's completely unnecessary and can 
                    // only cause bugs.  We will not parse anything using '[' stuff now
                    // and we should give a warning about seeing [strings] stuff.
                    // In V1.1 or V2, we can rip this out completely, I hope.
                    if (ch == '[')
                    {
                        String skip = sr.ReadLine();
                        if (skip.Equals("strings]"))
                            _logger.LogWarningWithCodeFromResources(null, fileName, sr.LineNumber - 1, 1, 0, 0, "GenerateResource.ObsoleteStringsTag");
                        else
                        {
                            throw new TextFileException(_logger.FormatResourceString("GenerateResource.UnexpectedInfBracket", "[" + skip), fileName, sr.LineNumber - 1, 1);
                        }
                        ch = sr.Read();
                        continue;
                    }

                    // Read in name
                    name.Length = 0;
                    while (ch != '=')
                    {
                        if (ch == '\r' || ch == '\n')
                            throw new TextFileException(_logger.FormatResourceString("GenerateResource.NoEqualsInLine", name), fileName, sr.LineNumber, sr.LinePosition);

                        name.Append((char)ch);
                        ch = sr.Read();
                        if (ch == -1)
                            break;
                    }
                    if (name.Length == 0)
                        throw new TextFileException(_logger.FormatResourceString("GenerateResource.NoNameInLine"), fileName, sr.LineNumber, sr.LinePosition);

                    // For the INF file, we must allow a space on both sides of the equals
                    // sign.  Deal with it.
                    if (name[name.Length - 1] == ' ')
                    {
                        name.Length = name.Length - 1;
                    }
                    ch = sr.Read(); // move past =
                    // If it exists, move past the first space after the equals sign.
                    if (ch == ' ')
                        ch = sr.Read();

                    // Read in value
                    value.Length = 0;

                    while (ch != -1)
                    {
                        // Did we read @"\r" or @"\n"?
                        bool quotedNewLine = false;
                        if (ch == '\\')
                        {
                            ch = sr.Read();
                            switch (ch)
                            {
                                case '\\':
                                    // nothing needed
                                    break;
                                case 'n':
                                    ch = '\n';
                                    quotedNewLine = true;
                                    break;
                                case 'r':
                                    ch = '\r';
                                    quotedNewLine = true;
                                    break;
                                case 't':
                                    ch = '\t';
                                    break;
                                case '"':
                                    ch = '\"';
                                    break;
                                case 'u':
                                    char[] hex = new char[4];
                                    int numChars = 4;
                                    int index = 0;
                                    while (numChars > 0)
                                    {
                                        int n = sr.Read(hex, index, numChars);
                                        if (n == 0)
                                            throw new TextFileException(_logger.FormatResourceString("GenerateResource.InvalidEscape", name.ToString(), (char)ch), fileName, sr.LineNumber, sr.LinePosition);
                                        index += n;
                                        numChars -= n;
                                    }
                                    try
                                    {
                                        ch = (char)UInt16.Parse(new String(hex), NumberStyles.HexNumber, CultureInfo.CurrentCulture);
                                    }
                                    catch (FormatException)
                                    {
                                        // We know about this one...
                                        throw new TextFileException(_logger.FormatResourceString("GenerateResource.InvalidHexEscapeValue", name.ToString(), new String(hex)), fileName, sr.LineNumber, sr.LinePosition);
                                    }
                                    catch (OverflowException)
                                    {
                                        // We know about this one, too...
                                        throw new TextFileException(_logger.FormatResourceString("GenerateResource.InvalidHexEscapeValue", name.ToString(), new String(hex)), fileName, sr.LineNumber, sr.LinePosition);
                                    }
                                    quotedNewLine = (ch == '\n' || ch == '\r');
                                    break;

                                default:
                                    throw new TextFileException(_logger.FormatResourceString("GenerateResource.InvalidEscape", name.ToString(), (char)ch), fileName, sr.LineNumber, sr.LinePosition);
                            }
                        }

                        // Consume endline...
                        //   Endline can be \r\n or \n.  But do not treat a 
                        //   quoted newline (ie, @"\r" or @"\n" in text) as a
                        //   real new line.  They aren't the end of a line.
                        if (!quotedNewLine)
                        {
                            if (ch == '\r')
                            {
                                ch = sr.Read();
                                if (ch == -1)
                                {
                                    break;
                                }
                                else if (ch == '\n')
                                {
                                    ch = sr.Read();
                                    break;
                                }
                            }
                            else if (ch == '\n')
                            {
                                ch = sr.Read();
                                break;
                            }
                        }

                        value.Append((char)ch);
                        ch = sr.Read();
                    }

                    // Note that value can be an empty string
                    AddResource(reader, name.ToString(), value.ToString(), fileName, sr.LineNumber, sr.LinePosition);
                }
            }
        }
Пример #37
0
 /// <summary>
 /// Read resources from an XML or binary format file
 /// </summary>
 /// <param name="reader">Appropriate IResourceReader</param>
 /// <param name="fileName">Filename, for error messages</param>
 private void ReadResources(ReaderInfo readerInfo, IResourceReader reader, String fileName)
 {
     using (reader)
     {
         IDictionaryEnumerator resEnum = reader.GetEnumerator();
         while (resEnum.MoveNext())
         {
             string name = (string)resEnum.Key;
             object value = resEnum.Value;
             AddResource(readerInfo, name, value, fileName);
         }
     }
 }
Пример #38
0
        /// <summary>
        /// Create a strongly typed resource class
        /// </summary>
        /// <param name="outFile">Output resource filename, for defaulting the class filename</param>
        /// <param name="inputFileName">Input resource filename, for error messages</param>
        private void CreateStronglyTypedResources(ReaderInfo reader, String outFile, String inputFileName, out String sourceFile)
        {
            CodeDomProvider provider = null;

            if (!TryCreateCodeDomProvider(_logger, _stronglyTypedLanguage, out provider))
            {
                sourceFile = null;
                return;
            }

            // Default the class name if we need to
            if (_stronglyTypedClassName == null)
            {
                _stronglyTypedClassName = Path.GetFileNameWithoutExtension(outFile);
            }

            // Default the filename if we need to
            if (_stronglyTypedFilename == null)
            {
                _stronglyTypedFilename = GenerateDefaultStronglyTypedFilename(provider, outFile);
            }
            sourceFile = this.StronglyTypedFilename;

            _logger.LogMessageFromResources("GenerateResource.CreatingSTR", _stronglyTypedFilename);

            // Generate the STR class
            String[] errors;
            bool generateInternalClass = !_stronglyTypedClassIsPublic;
            //StronglyTypedResourcesNamespace can be null and this is ok.
            // If it is null then the default namespace (=stronglyTypedNamespace) is used.
            CodeCompileUnit ccu = StronglyTypedResourceBuilder.Create(
                    reader.resourcesHashTable,
                    _stronglyTypedClassName,
                    _stronglyTypedNamespace,
                    _stronglyTypedResourcesNamespace,
                    provider,
                    generateInternalClass,
                    out errors
                    );

            CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
            using (TextWriter output = new StreamWriter(_stronglyTypedFilename))
            {
                provider.GenerateCodeFromCompileUnit(ccu, output, codeGenOptions);
            }

            if (errors.Length > 0)
            {
                _logger.LogErrorWithCodeFromResources("GenerateResource.ErrorFromCodeDom", inputFileName);
                foreach (String error in errors)
                {
                    _logger.LogErrorWithCodeFromResources("GenerateResource.CodeDomError", error);
                }
            }
            else
            {
                // No errors, and no exceptions - we presumably did create the STR class file
                // and it should get added to FilesWritten. So set a flag to indicate this.
                _stronglyTypedResourceSuccessfullyCreated = true;
            }
        }
Пример #39
0
        /// <summary>
        /// Write resources from the resources ArrayList to the specified output file
        /// </summary>
        /// <param name="filename">Output resources file</param>
        private void WriteResources(ReaderInfo reader, String filename)
        {
            Format format = GetFormat(filename);
            switch (format)
            {
                case Format.Text:
                    WriteTextResources(reader, filename);
                    break;

                case Format.XML:
                    WriteResources(reader, new ResXResourceWriter(filename)); // closes writer for us
                    break;

                case Format.Assembly:
                    _logger.LogErrorFromResources("GenerateResource.CannotWriteAssembly", filename);
                    break;

                case Format.Binary:
                    WriteResources(reader, new ResourceWriter(filename)); // closes writer for us
                    break;

                default:
                    // We should never get here, we've already checked the format
                    Debug.Fail("Unknown format " + format.ToString());
                    break;
            }
        }
Пример #40
0
        /// <summary>
        /// Reads the resources out of the specified file and populates the
        /// resources hashtable.
        /// </summary>
        /// <param name="filename">Filename to load</param>
        /// <param name="shouldUseSourcePath">Whether to resolve paths in the 
        /// resources file relative to the resources file location</param>
        /// <param name="outFileOrDir"> Output file or directory. </param>
        private void ReadResources(String filename, bool shouldUseSourcePath, String outFileOrDir)
        {
            Format format = GetFormat(filename);

            if (format == Format.Assembly) // Multiple input .resources files within one assembly
            {
                ReadAssemblyResources(filename, outFileOrDir);
            }
            else
            {
                ReaderInfo reader = new ReaderInfo();
                _readers.Add(reader);
                switch (format)
                {
                    case Format.Text:
                        ReadTextResources(reader, filename);
                        break;

                    case Format.XML:
                        ResXResourceReader resXReader = null;
                        if (_typeResolver != null)
                        {
                            resXReader = new ResXResourceReader(filename, _typeResolver);
                        }
                        else
                        {
                            resXReader = new ResXResourceReader(filename);
                        }

                        if (shouldUseSourcePath)
                        {
                            String fullPath = Path.GetFullPath(filename);
                            resXReader.BasePath = Path.GetDirectoryName(fullPath);
                        }
                        // ReadResources closes the reader for us
                        ReadResources(reader, resXReader, filename);
                        break;

                    case Format.Binary:
                        ReadResources(reader, new ResourceReader(filename), filename); // closes reader for us
                        break;

                    default:
                        // We should never get here, we've already checked the format
                        Debug.Fail("Unknown format " + format.ToString());
                        return;
                }
                _logger.LogMessageFromResources(MessageImportance.Low, "GenerateResource.ReadResourceMessage", reader.resources.Count, filename);
            }
        }