Inheritance: Singleton, IServer
Exemplo n.º 1
0
		public Base(Server.Game.Api gsApi)
		{
			if (gsApi != null)
				this.gsApi = gsApi;
			else
				throw new ArgumentNullException();
		}
Exemplo n.º 2
0
 public FavoriteServer(Server server) {
     _queryMode = server.QueryMode;
     _address = server.Address;
     _name = server.Name;
     _mod = String.Join(";", server.Mods); // Loss of info
     _gameName = server.GameName;
 }
Exemplo n.º 3
0
 /// <summary>
 /// Opens a HTTP listener on specific TCP bindings
 /// </summary>
 /// <param name="bindings"></param>
 /// <param name="callbackId"></param>
 public bool _listen(string binding, string callbackId) {
     // Start & Run HTTP daemon
     try
     {
         // Initialize URI for binding
         int port;
         if (Int32.TryParse(binding, out port)) { this.binding = new Uri(String.Format("http://localhost:{0}/", port)); }
         else if (!binding.Contains("http")) { this.binding = new Uri(String.Format("http//{0}", binding)); }
         else { this.binding = new Uri(binding); }
         if (server != null && server.listener != null)
         {
             // Server already exists, add a new binding & callback
             server.listener.Stop();
             server.listener.Prefixes.Add(this.binding.AbsoluteUri);
             server.listener.Start();
             processes.Add(callbackId, server);
         } else {
             // No server, create a new instance.
             server = new Server();
             server.listener.Prefixes.Add(this.binding.AbsoluteUri);
             server.listener.Start();
             processes.Add(callbackId, server);
         }
         Console.xdebug(String.Format("WebServer Listening on {0}", this.binding.AbsoluteUri));
         return true;
     }
     catch (Exception ex)
     {
         // Console.error(String.Format("Error listening on binding: {0}", binding));
         this.server = null;
         this.binding = null;
         return false;
     }
 }
Exemplo n.º 4
0
        static ServerStatus hostServer(ServerSettings.ConfigStore settings)
        {
            Server server = new Server(settings);

            try
            {
                server.hostingLoop();
            }
            catch (Exception e)
            {
                Log.Error("Unexpected exception encountered! Crash report written to log file");
                Log.Error(e.ToString());
                if (server.threadExceptionStackTrace != null && server.threadExceptionStackTrace.Length > 0)
                {
                    Log.Error("Stacktrace: ");
                    Log.Error(server.threadExceptionStackTrace);
                }
                //server.clearState();
                //return ServerStatus.CRASHED;
            }

            server.clearState();

            if (server.stop)
                return ServerStatus.STOPPED;

            if (!settings.autoRestart || server.quit)
                return ServerStatus.QUIT;

            return ServerStatus.RESTARTING;
        }
Exemplo n.º 5
0
    public Dictionary<Channel, List<User>> GetOfficeChannels(Server NewServer)
    {
        //Console.WriteLine("Scanning for office channels");

        Dictionary<Channel, List<User>> OfficeChannels = new Dictionary<Channel, List<User>>();
        foreach (Channel ServerChannel in NewServer.AllChannels)
        {
            if (ServerChannel.Type == ChannelType.Voice)
            {
                if (ServerChannel.Name.Contains("Office"))
                {
                    Match NameMatch = Regex.Match(ServerChannel.Name, "(.+?)'s Office");
                    if (NameMatch.Success)
                    {
                        List<User> OfficeUsers = NewServer.FindUsers(NameMatch.Groups[1].Value, exactMatch: true).Where(U => U.ServerPermissions.MoveMembers).ToList();
                        if (OfficeUsers.Count > 0)
                        {
                            OfficeChannels[ServerChannel] = OfficeUsers;
                            //await ServerChannel.Edit(maxusers: 2);
                            //Console.WriteLine(($"Registered Office Channel '{ServerChannel}' with users [{string.Join(", ", OfficeUsers)}]"));
                        }
                    }
                }
            }
        }
        return OfficeChannels;
    }
Exemplo n.º 6
0
        public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
        {
            Mobile pm = ( Mobile )sender.Mobile;

            if( pm == null )
                return;

            switch (info.ButtonID)
            {
                case 2:
                    {
                        TextRelay text = info.GetTextEntry( 1 );

                        if (text == null || text.Text == "")
                        {
                            pm.CloseGump(typeof(AccountSearch));
                            pm.SendGump(new AccountSearch());
                            return;
                        }

                        ArrayList authors = new ArrayList();

                        if (ForumCore.AuthorExists( out authors, text.Text))
                        {
                            pm.CloseGump( typeof(AccountListingGump));
                            pm.SendGump( new AccountListingGump( authors, 0 ) );
                        }
                        else
                        {
                            pm.SendMessage("Either that player does not exist, or no posts have been made by that player.");
                        }
                        break;
                    }
            }
        }
 public DatabaseHelper(string connectionString)
 {
     if (Server == null)
     {
         Server = GetServer(connectionString);
     }
 }
Exemplo n.º 8
0
		public OnGraph(Server.Game.Api gsApi)
			: base(gsApi)
		{
			gsApi.FinishMoving += (Model.Creature creature) =>
			{
				if (gsApi.World.Me == creature)
				{
					var current = Target;
					if (current.Nigh.Count > 1)
					{
						var variants = new List<Model.Graph.Node>();
						foreach(var node in current.Nigh)
							if(!node.Equals(Previous))
								variants.Add(node);
						var index = Random.Next(variants.Count);
						foreach (var node in variants)
							if (index-- == 0)
							{
								Target = node;
								break;
							}
					}
					else
						Target = current.Nigh.First();
					Previous = current;

					gsApi.MoveTo(Target.Point);
				}
			};
		}
Exemplo n.º 9
0
        private void ManageTables_Load(object sender, System.EventArgs e)
        {
            ServerConnection ServerConn;
            ServerConnect scForm;
            DialogResult dr;

            // Display the main window first
            this.Show();
            Application.DoEvents();

            ServerConn = new ServerConnection();
            scForm = new ServerConnect(ServerConn);
            dr = scForm.ShowDialog(this);
            if ((dr == DialogResult.OK) &&
                (ServerConn.SqlConnectionObject.State == ConnectionState.Open))
            {
                SqlServerSelection = new Server(ServerConn);
                if (SqlServerSelection != null)
                {
                    this.Text = Properties.Resources.AppTitle + SqlServerSelection.Name;

                    // Refresh database list
                    ShowDatabases(true);
                }
            }
            else
            {
                this.Close();
            }
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Server srv = new Server(@"SERVER");
            Database db = srv.Databases["DB"];

            Scripter stpsc = new Scripter(srv);
            // This option will script the tables with the procedures
            stpsc.Options.WithDependencies = false;

            foreach (StoredProcedure stp in db.StoredProcedures)
            {
                if (stp.IsSystemObject == false)
                {
                    Console.WriteLine("/* Create script for procedure " + stp.Name + " */");
                    System.Collections.Specialized.StringCollection sc2 = stpsc.Script(new Urn[] { stp.Urn });

                    foreach (string sp in sc2)
                    {
                        Console.WriteLine("Migrating procedure " + stp.Name + "... ");
                        using (var scon = Connections.Connect())
                        {
                            SqlCommand runit = new SqlCommand(sp, scon);
                            runit.ExecuteNonQuery();
                            runit.Dispose();
                            scon.Close();
                        }
                    }

                    Console.WriteLine("\n");

                }
            }
        }
Exemplo n.º 11
0
        internal static FolderDatasetList Parse(Server oServer, string strKey, int iTimestamp, System.Xml.XmlDocument oCatalog, out string strEdition)
        {
            strEdition = string.Empty;
             ArrayList oList = new ArrayList();

             // --- get the catalog edition ---

             System.Xml.XmlNodeList oNodeList = oCatalog.SelectNodes("//" + Geosoft.Dap.Xml.Common.Constant.Tag.CONFIGURATION_TAG);
             if (oNodeList != null && oNodeList.Count != 0)
             {
            System.Xml.XmlNode oAttr = oNodeList[0].Attributes.GetNamedItem(Geosoft.Dap.Xml.Common.Constant.Attribute.VERSION_ATTR);
            if (oAttr != null)
               strEdition = oAttr.Value;
             }

             oNodeList = oCatalog.SelectNodes("//" + Geosoft.Dap.Xml.Common.Constant.Tag.ITEM_TAG);
             if (oNodeList != null)
             {
            foreach (System.Xml.XmlElement oDatasetNode in oNodeList)
            {
               Geosoft.Dap.Common.DataSet oDataSet;
               oServer.Command.Parser.DataSet(oDatasetNode, out oDataSet);
               oList.Add(oDataSet);
            }
             }
             return new FolderDatasetList(strKey, iTimestamp, oList);
        }
Exemplo n.º 12
0
		protected override IEnumerable<DbParameter> CoreGetColumnParameters(Type connectionType, string dataSourceTag, Server server, Database database, Schema schema, Table table)
		{
			if ((object)connectionType == null)
				throw new ArgumentNullException(nameof(connectionType));

			if ((object)dataSourceTag == null)
				throw new ArgumentNullException(nameof(dataSourceTag));

			if ((object)server == null)
				throw new ArgumentNullException(nameof(server));

			if ((object)database == null)
				throw new ArgumentNullException(nameof(database));

			if ((object)schema == null)
				throw new ArgumentNullException(nameof(schema));

			if ((object)table == null)
				throw new ArgumentNullException(nameof(table));

			if (dataSourceTag.SafeToString().ToLower() == ODBC_SQL_SERVER_DATA_SOURCE_TAG)
			{
				return new DbParameter[]
						{
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.ReflectionFascadeLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P1", server.ServerName),
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.ReflectionFascadeLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P2", database.DatabaseName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P3", schema.SchemaName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P4", table.TableName)
						};
			}

			throw new ArgumentOutOfRangeException(string.Format("dataSourceTag: '{0}'", dataSourceTag));
		}
Exemplo n.º 13
0
        public Form1()
        {
            InitializeComponent();
            listView1.Items.Clear();
            listView1.View = View.Details;
            listView1.Columns.Add("Path");
            listView1.Columns[0].Width = listView1.Width - 4;
            listView1.HeaderStyle = ColumnHeaderStyle.None;

            string dir = "D:\\iTunes Music\\Music";
            List<System.IO.FileInfo> files = new List<FileInfo>();
            List<string> dirs = new List<string>(Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories));
            foreach (var subDir in dirs)
            {
                FileInfo file = new FileInfo(subDir);
                TagLib.File sameFile = TagLib.File.Create(subDir);
                Console.WriteLine(subDir);
                int length = sameFile.Tag.Performers.Length;
                listView1.Items.Add(new ListViewItem("Title: " + sameFile.Tag.Title + "  -  Artist: " + (length > 0 ? sameFile.Tag.Performers[0] : "")));
            }
            Console.WriteLine("\n{0} directories found.", dirs.Count);

            Server server = new Server("http://*:8000/");
            server.AddRequestHandler(new DiffSyncRequestHandler());
            server.Start();
        }
Exemplo n.º 14
0
        private Program()
        {
            Log.Info("Loading settings");
            Config.Load();

            AppDomain.CurrentDomain.UnhandledException += (s, e) => {
                Log.Fatal(e.ExceptionObject.ToString());
            };

            Log.Info("Connecting to database");
            Database.Instance.Connect();

            String region = Database.Instance.GetServerRegion(Config.ServerId);
            if (region == String.Empty)
                Log.Fatal("Server region not found");

            Database.Instance.CleanServerStatus(Config.ServerId);

            String listen = String.Format("ws://{0}:{1}/", Config.Host, Config.Port);
            Server server = new Server(region);
            server.Start(listen);

            Database.Instance.ServerStatus(Config.ServerId, Config.Host + ":" + Config.Port, true);

            AppDomain.CurrentDomain.ProcessExit += (s, e) =>
            {
                Database.Instance.ServerStatus(Config.ServerId, null, false);
            };

            while(true)
                Console.ReadKey();
        }
        public AggiungiServerDialogBox()
        {
            InitializeComponent();
            server = new Server(){Name="Server1", IP = "192.168.1.1", ControlPort=1500};

            textGrid.DataContext = server;
        }
Exemplo n.º 16
0
        private void OnClientConnect(IAsyncResult AcceptAsync)
        {
            try
            {
                Socket Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Sock = ListenerSock.EndAccept(AcceptAsync);
                Server ServerSock = new Server(Sock);
                //RaiseEvent if event is linked
                if (Connected != null)
                {
                    Connected(ServerSock);
                }
            }
            catch
            {

            }
            finally
            {
                ListenerSock.Dispose();
                ListenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];
                ListenerSock.Bind(new IPEndPoint(hostIP, m_Port));
                ListenerSock.Listen(0);
                ListenerSock.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
        }
Exemplo n.º 17
0
 public void Run(ManagerLogger managerLogger, Server server, NetIncomingMessage inc, PlayerAndConnection playerAndConnection, GameRoom gameRoom)
 {
     managerLogger.AddLogMessage("server", "New connection...");
     var data = inc.ReadByte();
     if (data == (byte)PacketType.Login)
     {
         managerLogger.AddLogMessage("server", "..connection accpeted.");
         playerAndConnection = CreatePlayer(inc, gameRoom.Players, gameRoom.ManagerCamera);
         inc.SenderConnection.Approve();
         var outmsg = server.NetServer.CreateMessage();
         outmsg.Write((byte)PacketType.Login);
         outmsg.Write(true);
         outmsg.Write(gameRoom.Players.Count);
         for (int n = 0; n < gameRoom.Players.Count; n++)
         {
             var p = gameRoom.Players[n];
             outmsg.Write(p.Player.Username);
             outmsg.WriteAllProperties(p.Player.Position);
         }
         server.NetServer.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0);
         var command = new PlayerPositionCommand();
         command.Run(managerLogger, server,inc,playerAndConnection,gameRoom);
         server.SendNewPlayerEvent(playerAndConnection.Player.Username, gameRoom.GameRoomId);
     }
     else
     {
         inc.SenderConnection.Deny("Didn't send correct information.");
     }
 }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            Server srv = new Server(@"SERVER\INSTANCE");
            string dbName = "DATABASE";
            Database db = srv.Databases[dbName];

            DateTime now = DateTime.Now;
            DateTime dt = now.AddDays(-3);
            string ndt;
            ndt = Convert.ToString(now.Year) + "" + Convert.ToString(now.Month) + "" + Convert.ToString(now.Day);
            DateTime dbDate = db.LastBackupDate;
            string name = db.Name;

            if (dt > dbDate)
            {
                using (var scon = Connections.Connect())
                {
                    SqlCommand back = new SqlCommand("BACKUP DATABASE " + name + " TO DISK = 'C:\\Backups\\" + name + "_" + ndt + ".BAK'", scon);
                    back.ExecuteNonQuery();
                    scon.Close();
                }
            }
            Console.WriteLine("Database backed up");
            Console.ReadLine();
        }
Exemplo n.º 19
0
 void server_ReceivedRequest(Server.Request r)
 {
     if (this.listBox1.InvokeRequired) {
         AddItemDelegate d = new AddItemDelegate(add);
         this.Invoke(d, new object[] { r.Code });
     }
 }
Exemplo n.º 20
0
		public static bool RunSqlScriptOnConnection(string connectionString, string filePath, out string errorMessage)
		{
			try
			{
				var scriptContents = File.ReadAllText(filePath);
				var sqlConnection = new SqlConnection(connectionString);
				var server = new Server(new ServerConnection(sqlConnection));
				server.ConnectionContext.ExecuteNonQuery(scriptContents);

				errorMessage = string.Empty;

				return true;
			}
			catch (ExecutionFailureException ex)
			{
				var sqlException = ex.InnerException as SqlException;
				if (sqlException != null)
				{
					errorMessage = string.Format("At line {0}:\n{1}", sqlException.LineNumber, sqlException.Message);
				}
				else if (ex.InnerException != null)
				{
					errorMessage = ex.InnerException.Message;
				}
				else
					errorMessage = ex.Message;
			}
			catch (Exception ex)
			{
				errorMessage = ex.Message;
			}

			return false;
		}
Exemplo n.º 21
0
 public void Delete(string databaseName)
 {
     var server = new Server(Settings.DefaultConnection.Host);
     try
     {
         server.ConnectionContext.LoginSecure = true;
         server.ConnectionContext.Connect();
         if (!server.Databases.Contains(databaseName))
         {
             Logger.WriteLine("Did not find database '{0}'", databaseName);
             return;
         }
         Logger.Write("Dropping database [{0}]...", databaseName);
         server.Databases[databaseName].Drop();
         Logger.WriteLine("OK");
     }
     finally
     {
         if (server.ConnectionContext.IsOpen)
         {
             Logger.Write("Closing connection...");
             server.ConnectionContext.Disconnect();
             Logger.WriteLine("OK");
         }
     }
 }
Exemplo n.º 22
0
        public override void Execute(Server server, MinecraftClient user, string text, params string[] parameters)
        {
            bool add = false;
            var current = server.MinecraftServer.GetLevel(user).Time;
            long? time = null;
            if (parameters.Length == 0)
            {
                user.SendChat("The current time is " + current + ", or " + LongToTimeString(current));
                return;
            }
            if (parameters[0].ToLower() == "day")
                time = 0;
            else if (parameters[0].ToLower() == "night")
                time = 12000;
            else if (parameters[0].ToLower() == "noon")
                time = 6000;
            else if (parameters[0].ToLower() == "midnight")
                time = 18000;
            else
            {
                string timeString;
                if (parameters[0].ToLower() == "set" && parameters.Length > 1)
                    timeString = parameters[1];
                else if (parameters[0].ToLower() == "add" && parameters.Length > 1)
                {
                    timeString = parameters[1];
                    add = true;
                }
                else
                    timeString = parameters[0];
                if (timeString.Contains(":"))
                {
                    try
                    {
                        time = TimeStringToLong(timeString);
                    }
                    catch { }
                }
                else
                {
                    long _time;
                    if (long.TryParse(timeString, out _time))
                        time = _time;
                }
                if (add)
                    time += current;
            }

            if (time == null)
            {
                user.SendChat(ChatColors.Red + "Invalid time specified.");
                return;
            }

            time = time.Value % 24000;

            server.MinecraftServer.GetLevel(user).Time = time.Value; // TODO: Add event listener in Craft.Net
            server.SendChatToGroup("server.op", ChatColors.Gray + user.Username + " set the time in " + user.World.Name +
                " to " + time.Value + ", or " + LongToTimeString(time.Value));
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            Debug.Listeners.Add(new ConsoleTraceListener());
            Debug.AutoFlush = true;

            string url = "http://localhost:8081/";
            var server = new Server(url);
            server.Configuration.DisconnectTimeout = TimeSpan.Zero;

            // Map connections
            server.MapConnection<MyConnection>("/echo")
                  .MapConnection<Raw>("/raw")
                  .MapHubs();

            server.Start();

            Console.WriteLine("Server running on {0}", url);

            while (true)
            {
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.X)
                {
                    break;
                }
            }
        }
        static void Main(string[] args)
        {
            // connect to default instance on local machine
            Server server = new Server(".");

            ScriptingOptions so = new ScriptingOptions();
            so.Triggers = true;

            Microsoft.SqlServer.Management.Smo.Transfer tr = new Transfer();

            // Note: Make sure that srcdb exists on local machine's default instance
            tr.Database = server.Databases["srcdb"];
            tr.DestinationDatabase = "targetdb";
            tr.DestinationServer = ".";
            tr.DestinationLoginSecure = true;
            tr.Options = so;

            // Enumerate scripts
            List<string> scripts = tr.EnumScriptTransfer().ToList<string>();

            // print generated scripts to console
            foreach (string script in scripts)
            {
                Console.WriteLine(script);
                Console.WriteLine("GO");
            }
        }
Exemplo n.º 25
0
 public SnapshotManagement(SqlRepository Repository)
 {
     _Repository = Repository;
     _Server = new Server(
         new ServerConnection(Repository.Connection)
     );
 }
        /// <summary>
        /// PluginManager class constructor
        /// </summary>
        /// <param name="pluginPath">Path to plugin directory</param>
        /// <param name="server">Current Server instance</param>
        public PluginManager(String pluginPath, Server server)
        {
            this.pluginPath = pluginPath;
            this.server = server;

            plugins = new Dictionary<String, Plugin>();
        }
Exemplo n.º 27
0
 public DataManager(Client<Message> client, Server<Message> server)
 {
     _networkClient = client;
     _networkServer = server;
     networkTimeout = -1;
     int.TryParse(ConfigurationManager.AppSettings[timeoutConfigString], out networkTimeout);
 }
Exemplo n.º 28
0
		public HttpHandlerContext(Server server, HttpRequestProcessor.Host host, Connection connection, IIdentity identity)
		{
			Server = server;
			Host = host;
			Connection = connection;
			Identity = identity;
		}
Exemplo n.º 29
0
 /// <summary>
 /// Creates an instance of the object.
 /// </summary>
 /// <param name="dataPortalContext">
 /// Data portal context object.
 /// </param>
 /// <param name="objectType">
 /// Business object type.
 /// </param>
 /// <param name="obj">
 /// Criteria or business object for request.
 /// </param>
 /// <param name="operation">
 /// Data portal operation being performed.
 /// </param>
 public DataPortalEventArgs(Server.DataPortalContext dataPortalContext, Type objectType, object obj, DataPortalOperations operation)
 {
     _dataPortalContext = dataPortalContext;
       _operation = operation;
       _objectType = objectType;
       _object = obj;
 }
Exemplo n.º 30
0
        public override bool OnCraft( bool exceptional, bool makersMark, Mobile from, Server.Engines.Craft.CraftSystem craftSystem, Type typeRes, BaseTool tool, Server.Engines.Craft.CraftItem craftItem, int resHue )
        {
            if ( exceptional )
                ArmorAttributes.MageArmor = 1;

            return base.OnCraft( exceptional, makersMark, from, craftSystem, typeRes, tool, craftItem, resHue );
        }
Exemplo n.º 31
0
        //======================== Method For report File Format================================================//////

        public void ExportToPdf(DataTable myDataTable, params string[] headerList)
        {
            if (myDataTable.Rows.Count == 0)
            {
                return;
            }

            Document pdfDoc = new Document(PageSize.A4, 10, 10, 8, 8);

            try
            {
                PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
                pdfDoc.Open();
                //Chunk c = new Chunk( "HSBC", FontFactory.GetFont("Verdana", 11));
                //Paragraph p = new Paragraph();
                //p.Alignment = Element.ALIGN_CENTER;
                //p.Add(c);
                //pdfDoc.Add(p);

                string imageFilePath = Server.MapPath("~/Images") + "\\" + "hsbc.jpg";

                iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
                //Resize image depend upon your need
                //jpg.ScaleToFit(80f, 60f);
                //Give space before image
                jpg.SpacingBefore = 0f;
                //Give some space after the image
                jpg.SpacingAfter = 1f;
                jpg.Alignment    = Element.ALIGN_CENTER;
                pdfDoc.Add(jpg);

                Font      font8 = FontFactory.GetFont("ARIAL", 7);
                DataTable dt    = myDataTable;
                if (dt != null)
                {
                    //Craete instance of the pdf table and set the number of column in that table
                    PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                    PdfPCell  PdfPCell = null;

                    Font fnt = new Font(Font.HELVETICA, 8);

                    foreach (string columheader in headerList)
                    {
                        PdfTable.AddCell(new iTextSharp.text.Phrase(columheader, fnt));
                    }

                    for (int rows = 0; rows < dt.Rows.Count; rows++)
                    {
                        for (int column = 0; column < dt.Columns.Count; column++)
                        {
                            PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                            PdfTable.AddCell(PdfPCell);
                        }
                    }
                    //PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
                    pdfDoc.Add(PdfTable); // add pdf table to the document
                }
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
                System.Web.HttpContext.Current.Response.Write(pdfDoc);

                Response.Flush();
                Response.End();
                //HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (DocumentException de)
            {
                System.Web.HttpContext.Current.Response.Write(de.Message);
            }
            catch (IOException ioEx)
            {
                System.Web.HttpContext.Current.Response.Write(ioEx.Message);
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write(ex.Message);
            }
        }
Exemplo n.º 32
0
 public void SendPartySettingToClient(long connectionId, PartyData party)
 {
     Server.SendPartySetting(connectionId, MsgTypes.UpdateParty, party.id, party.shareExp, party.shareItem);
 }
Exemplo n.º 33
0
 public void SendChangePartyLeaderToClient(long connectionId, PartyData party)
 {
     Server.SendChangePartyLeader(connectionId, MsgTypes.UpdateParty, party.id, party.leaderId);
 }
Exemplo n.º 34
0
 public void SendCreatePartyToClient(long connectionId, PartyData party)
 {
     Server.SendCreateParty(connectionId, MsgTypes.UpdateParty, party.id, party.shareExp, party.shareItem, party.leaderId);
 }
Exemplo n.º 35
0
 public ShardRequestBase <T> CreateUnicastRequest <T>(Server destination, Message message)
 {
     return(new ShardUnicastRequest <T>(this, destination, message));
 }
Exemplo n.º 36
0
        private void ConnectPrimary(Address primary)
        {
            // check if the shardConnected event is required to be raised
            bool shardConnected = false;

            // If primary is null, it means the respective shard has no primary anymore so
            if (primary == null)
            {
                if (_remoteShardChannel != null)
                {
                    ((DualChannel)_remoteShardChannel).ShouldTryReconnecting = false;
                    _remoteShardChannel.Disconnect();
                    _remoteShardChannel = null;
                }
            }
            else
            {
                if (_remoteShardChannel != null)
                {
                    if (_remoteShardChannel.PeerAddress.Equals(primary) && ((IDualChannel)this._remoteShardChannel).Connected)
                    {
                        return;
                    }
                }


                bool isConnected = false;
                IRequestResponseChannel channel = factory.GetChannel(primary.IpAddress.ToString(), _shardPort, context.LocalAddress.IpAddress.ToString(), SessionTypes.Shard, _traceProvider, _channelFormatter);
                try
                {
                    isConnected = channel.Connect(false);
                }
                catch (ChannelException e)
                {
                    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                    {
                        LoggerManager.Instance.ShardLogger.Error("Error: RemoteShard.OnPrimaryChanged()", e.ToString());
                    }
                }
                //catch (Exception ex)
                //{
                //    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                //        LoggerManager.Instance.ShardLogger.Error("Error: RemoteShard.OnPrimaryChanged()", e.ToString());
                //}

                if (isConnected)
                {
                    SessionInfo info = new SessionInfo();
                    info.Cluster = this.Context.ClusterName;
                    info.Shard   = this.Context.LocalShardName;

                    channel.SendMessage(info, true);

                    lock (_onChannel)
                    {
                        _remoteShardChannel = _resolveDispute.GetValidChannel(_resolveDispute.SetConnectInfo(channel as IDualChannel, ConnectInfo.ConnectStatus.CONNECT_FIRST_TIME), _remoteShardChannel);
                        ((IDualChannel)_remoteShardChannel).StartReceiverThread();
                        ((IDualChannel)_remoteShardChannel).RegisterRequestHandler(this);
                        shardConnected = true;
                    }
                    lock (_onPrimary)
                    {
                        _primary = new Server(new Address(primary.IpAddress.ToString(), primary.Port), Status.Running);
                    }
                }
            }

            if (shardConnected)
            {
                ShardConnected();
            }
        }
Exemplo n.º 37
0
        public bool OnSessionEstablished(Session session)
        {
            // check if the shardConnected event is required to be raised
            bool   shardConnected           = false;
            Server server                   = new Server(new Common.Net.Address(session.IP.ToString(), this._shardPort), Status.Initializing);
            IRequestResponseChannel channel = factory.GetChannel(session.Connection, session.IP.ToString(), this._shardPort, context.LocalAddress.ToString(), SessionTypes.Shard, _traceProvider, _channelFormatter);

            LoggerManager.Instance.SetThreadContext(new LoggerContext()
            {
                ShardName = _name != null ? _name : "", DatabaseName = ""
            });
            try
            {
                if (_remoteShardChannel != null && !((IDualChannel)_remoteShardChannel).Connected && _remoteShardChannel.PeerAddress.Equals(server))
                {
                    session.Connection.Disconnect();
                    //throw new ChannelException("already connected with shard"+_name);
                }

                if (channel.Connect(false))
                {
                    ConnectInfo.ConnectStatus status = ConnectInfo.ConnectStatus.CONNECT_FIRST_TIME;
                    if (_remoteShardChannel != null && _remoteShardChannel.PeerAddress.Equals(server.Address))
                    {
                        status = ConnectInfo.ConnectStatus.RECONNECTING;
                    }

                    lock (_onChannel)
                    {
                        _remoteShardChannel = _resolveDispute.GetValidChannel(_resolveDispute.SetConnectInfo(channel as IDualChannel, status), _remoteShardChannel);
                        ((IDualChannel)_remoteShardChannel).StartReceiverThread();
                        ((IDualChannel)_remoteShardChannel).RegisterRequestHandler(this);

                        shardConnected = true;
                    }
                    if (_primary != null && !_primary.Address.Equals(server.Address))
                    {
                        BrokenConnectionInfo info = new BrokenConnectionInfo();
                        info.BrokenAddress = _primary.Address;
                        info.SessionType   = SessionTypes.Shard;
                        _connectionRestoration.UnregisterListener(info);
                    }
                    lock (_onPrimary)
                    {
                        _primary = server;
                    }

                    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsInfoEnabled)
                    {
                        LoggerManager.Instance.ShardLogger.Info("RemoteShard.OnSessionEstd()", "Session of the shard " + _name + " estd successfully");
                    }
                    return(IsStarted = true);
                }
                else
                {
                    return(false);
                }
            }
            catch (ChannelException e)
            {
                if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                {
                    LoggerManager.Instance.ShardLogger.Error("Error: RemoteShard.OnSessionEstd()", e.ToString());
                }
                return(false);
            }
            finally
            {
                if (shardConnected)
                {
                    ShardConnected();
                }
            }
        }
        public ActionResult IncidentType()
        {
            ViewBag.EGHLayout = "RGE.IncidentType";
            RGEContext   db       = null;
            ActionResult view     = View("Index");
            string       menuitem = this.HttpContext.Request.Params["menuitem"] ?? "Empty";

            try
            {
                db          = new RGEContext();
                ViewBag.msg = "Соединение с базой данных установлено";  // debug
                view        = View("IncidentType", db);
                if (menuitem.Equals("IncidentType.Create"))
                {
                    view = View("IncidentTypeCreate");
                }
                else if (menuitem.Equals("IncidentType.Delete"))
                {
                    string type_code_item = this.HttpContext.Request.Params["type_code"];
                    if (type_code_item != null)
                    {
                        int c = 0;
                        if (int.TryParse(type_code_item, out c))
                        {
                            IncidentType it = new IncidentType();
                            if (EGH01DB.Types.IncidentType.GetByCode(db, c, out it))
                            {
                                view = View("IncidentTypeDelete", it);
                            }
                        }
                    }
                }
                else if (menuitem.Equals("IncidentType.Update"))
                {
                    string type_code_item = this.HttpContext.Request.Params["type_code"];
                    if (type_code_item != null)
                    {
                        int c = 0;
                        if (int.TryParse(type_code_item, out c))
                        {
                            IncidentType it = new IncidentType();
                            if (EGH01DB.Types.IncidentType.GetByCode(db, c, out it))
                            {
                                view = View("IncidentTypeUpdate", it);
                            }
                        }
                    }
                }
                else if (menuitem.Equals("IncidentType.Excel"))
                {
                    EGH01DB.Types.IncidentTypeList list = new IncidentTypeList(db);
                    XmlNode     node  = list.toXmlNode();
                    XmlDocument doc   = new XmlDocument();
                    XmlNode     nnode = doc.ImportNode(node, true);
                    doc.AppendChild(nnode);
                    doc.Save(Server.MapPath("~/App_Data/IncidentType.xml"));
                    view = View("Index");

                    view = File(Server.MapPath("~/App_Data/IncidentType.xml"), "text/plain", "Типы инцидентов.xml");
                }
            }
            catch (RGEContext.Exception e)
            {
                ViewBag.msg = e.message;
            }
            catch (Exception e)
            {
                ViewBag.msg = e.Message;
            }

            return(view);
        }
Exemplo n.º 39
0
        protected override ExitCode RunCommand(Preprocessor preprocessor)
        {
            // Get the standard input stream
            _configOptions.Stdin = StandardInputReader.Read();

            // Fix the root folder and other files
            DirectoryPath currentDirectory = Environment.CurrentDirectory;

            _configOptions.RootPath       = _configOptions.RootPath == null ? currentDirectory : currentDirectory.Combine(_configOptions.RootPath);
            _logFilePath                  = _logFilePath == null ? null : _configOptions.RootPath.CombineFile(_logFilePath);
            _configOptions.ConfigFilePath = _configOptions.RootPath.CombineFile(_configOptions.ConfigFilePath ?? "config.wyam");

            // Set up the log file
            if (_logFilePath != null)
            {
                Trace.AddListener(new SimpleFileTraceListener(_logFilePath.FullPath));
            }

            // Get the engine and configurator
            EngineManager engineManager = EngineManager.Get(preprocessor, _configOptions);

            if (engineManager == null)
            {
                return(ExitCode.CommandLineError);
            }

            // Configure and execute
            if (!engineManager.Configure())
            {
                return(ExitCode.ConfigurationError);
            }

            if (_verifyConfig)
            {
                Trace.Information("No errors. Exiting.");
                return(ExitCode.Normal);
            }

            TraceEnviornment(engineManager);

            if (!engineManager.Execute())
            {
                return(ExitCode.ExecutionError);
            }

            bool messagePump = false;

            // Start the preview server
            Server previewServer = null;

            if (_preview)
            {
                messagePump = true;
                DirectoryPath previewPath = _previewRoot == null
                    ? engineManager.Engine.FileSystem.GetOutputDirectory().Path
                    : engineManager.Engine.FileSystem.GetOutputDirectory(_previewRoot).Path;

                previewServer = PreviewServer.Start(previewPath, _previewPort, _previewForceExtension, _previewVirtualDirectory, _watch && !_noReload, _contentTypes);
            }

            // Start the watchers
            IDisposable inputFolderWatcher = null;
            IDisposable configFileWatcher  = null;

            if (_watch)
            {
                messagePump = true;

                Trace.Information("Watching paths(s) {0}", string.Join(", ", engineManager.Engine.FileSystem.InputPaths));
                inputFolderWatcher = new ActionFileSystemWatcher(
                    engineManager.Engine.FileSystem.GetOutputDirectory().Path,
                    engineManager.Engine.FileSystem.GetInputDirectories().Select(x => x.Path),
                    true,
                    "*.*",
                    path =>
                {
                    _changedFiles.Enqueue(path);
                    _messageEvent.Set();
                });

                if (_configOptions.ConfigFilePath != null)
                {
                    Trace.Information("Watching configuration file {0}", _configOptions.ConfigFilePath);
                    configFileWatcher = new ActionFileSystemWatcher(
                        engineManager.Engine.FileSystem.GetOutputDirectory().Path,
                        new[] { _configOptions.ConfigFilePath.Directory },
                        false,
                        _configOptions.ConfigFilePath.FileName.FullPath,
                        path =>
                    {
                        FilePath filePath = new FilePath(path);
                        if (_configOptions.ConfigFilePath.Equals(filePath))
                        {
                            _newEngine.Set();
                            _messageEvent.Set();
                        }
                    });
                }
            }

            // Start the message pump if an async process is running
            ExitCode exitCode = ExitCode.Normal;

            if (messagePump)
            {
                // Only wait for a key if console input has not been redirected, otherwise it's on the caller to exit
                if (!Console.IsInputRedirected)
                {
                    // Start the key listening thread
                    Thread thread = new Thread(() =>
                    {
                        Trace.Information("Hit Ctrl-C to exit");
                        Console.TreatControlCAsInput = true;
                        while (true)
                        {
                            // Would have prefered to use Console.CancelKeyPress, but that bubbles up to calling batch files
                            // The (ConsoleKey)3 check is to support a bug in VS Code: https://github.com/Microsoft/vscode/issues/9347
                            ConsoleKeyInfo consoleKey = Console.ReadKey(true);
                            if (consoleKey.Key == (ConsoleKey)3 || (consoleKey.Key == ConsoleKey.C && (consoleKey.Modifiers & ConsoleModifiers.Control) != 0))
                            {
                                _exit.Set();
                                _messageEvent.Set();
                                break;
                            }
                        }
                    })
                    {
                        IsBackground = true
                    };
                    thread.Start();
                }

                // Wait for activity
                while (true)
                {
                    _messageEvent.WaitOne(); // Blocks the current thread until a signal
                    if (_exit)
                    {
                        break;
                    }

                    // See if we need a new engine
                    if (_newEngine)
                    {
                        // Get a new engine
                        Trace.Information("Configuration file {0} has changed, re-running", _configOptions.ConfigFilePath);
                        engineManager.Dispose();
                        engineManager = EngineManager.Get(preprocessor, _configOptions);

                        // Configure and execute
                        if (!engineManager.Configure())
                        {
                            exitCode = ExitCode.ConfigurationError;
                            break;
                        }

                        TraceEnviornment(engineManager);

                        if (!engineManager.Execute())
                        {
                            exitCode = ExitCode.ExecutionError;
                        }

                        // Clear the changed files since we just re-ran
                        string changedFile;
                        while (_changedFiles.TryDequeue(out changedFile))
                        {
                        }

                        _newEngine.Unset();
                    }
                    else
                    {
                        // Execute if files have changed
                        HashSet <string> changedFiles = new HashSet <string>();
                        string           changedFile;
                        while (_changedFiles.TryDequeue(out changedFile))
                        {
                            if (changedFiles.Add(changedFile))
                            {
                                Trace.Verbose("{0} has changed", changedFile);
                            }
                        }
                        if (changedFiles.Count > 0)
                        {
                            Trace.Information("{0} files have changed, re-executing", changedFiles.Count);
                            if (!engineManager.Execute())
                            {
                                exitCode = ExitCode.ExecutionError;
                            }
                            previewServer?.TriggerReload();
                        }
                    }

                    // Check one more time for exit
                    if (_exit)
                    {
                        break;
                    }
                    Trace.Information("Hit Ctrl-C to exit");
                    _messageEvent.Reset();
                }

                // Shutdown
                Trace.Information("Shutting down");
                engineManager.Dispose();
                inputFolderWatcher?.Dispose();
                configFileWatcher?.Dispose();
                previewServer?.Dispose();
            }

            return(exitCode);
        }
Exemplo n.º 40
0
    protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {

        // Save file
        string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
        string fn = filename;
        filename = String.Format("IMCT_{0}_ORDER_{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), filename);
        AsyncFileUpload1.SaveAs(Server.MapPath("~/Files/") + filename);

        // HATC Order
        string CustCode = "40111011";
        filename = Server.MapPath("~/Files/") + filename;
        if (File.Exists(filename))
        {
            string line = string.Empty;
            using (StreamReader sr = new StreamReader(filename))
            {
                //using (SqlProcedure sp = new SqlProcedure("sp_IMCT_Order_ClearData"))
                //{
                //    sp.ExecuteNonQuery();
                //}
                int i = 1;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Length > 0)
                    {
                        if (!line.Contains("ISUZU"))
                        {
                            MyCompany.Models.IMCTOrderImport Order = new MyCompany.Models.IMCTOrderImport();
                            Order.OrderBy = CustCode;
                            Order.DeliveryDestination = line.Substring(120, 5).Trim();
                            Order.CustomerMatCode = line.Substring(35, 10).Trim();
                            Order.CustomerPO = line.Substring(2, 10).Trim();
                            Order.ReliabilityDevision = "P";
                            Order.DeliveryDate = Convert.ToDateTime(line.Substring(50, 4).Trim() + "-" + line.Substring(54, 2).Trim() + "-" + line.Substring(56, 2).Trim());
                            Order.Quantity = float.Parse(line.Substring(58, 6)).ToString().Trim();
                            Order.Unit = "ST";
                            Order.PlngPeriod = "D";
                            string[] materialTemp = SharedBusinessRules.getMaterial(line.Substring(35, 10).Trim().Replace(" ", ""), CustCode, line.Substring(120, 5).Trim(), "IMCT").Split(':');
                            if (materialTemp.Length > 1)
                            {
                                Order.SAPCode = materialTemp[0];
                                Order.PartsDevision = materialTemp[1];
                                Order.DeliveryDestinationCode = materialTemp[2];
                                Order.Key1 = materialTemp[3];
                                Order.Key2 = materialTemp[4];
                                Order.Key3 = materialTemp[5];
                            }
                            Order.AddCode = i.ToString();
                            Order.PlantCode = "";
                            Order.Arrivaltime = line.Substring(159, 2).Trim() + ":" + line.Substring(161, 2).Trim();
                            Order.FromTo = "RTP:" + line.Substring(120, 5).Trim();
                            Order.Filename = fn;
                            Order.Insert();
                            i++;
                        }
                    }
                }
                
                sr.Close();
            }

        }
    }
        protected void ButtonApply_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();

            if (obj.IsUserExist(txtEmailAddress.Text.Trim()) == true)
            {
                lblResult.Text = "* Your are registered user, please login to apply";
                return;
            }
            if (IsAlreadyApply() == true)
            {
                lblResult.Text = "* Your have already applied for this job";
                return;
            }

            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }


            SqlCommand comSave = new SqlCommand();
            SqlCommand comCode = new SqlCommand();
            Class1     Obj     = new Class1();

            if ((Obj.GetCode("File") == "-1") || (Obj.UniqueCode() == "-1"))
            {
                lblResult.Text = "Error Occurs";
                return;
            }
            String FileName = Obj.GetCode("File") + Obj.UniqueCode();

            /************************************Save File Code**********************************************************/
            if (FileUploadResume.HasFile)
            {
                string ext        = Path.GetExtension(FileUploadResume.FileName);
                string resumePath = Server.MapPath("Resume\\");
                if (ext.ToLower() == ".txt" || ext.ToLower() == ".doc" || ext.ToLower() == ".docx" || ext.ToLower() == ".pdf")
                {
                    //FileUpload2.FileName.Replace(FileUpload2.FileName, );
                    FileUploadResume.PostedFile.SaveAs(resumePath + FileName + ext);
                    // = FileUpload2.FileName.ToString();

                    ViewState["Resume"] = FileName + ext;
                }
                else
                {
                    lblResult.Text = "* Wrong file type for resume";
                    return;
                }
            }
            else
            {
                lblResult.Text = "* Wrong file type for resume";
                return;
            }

            /**********************************************************************************************/
            SqlTransaction Trans1 = connection.BeginTransaction();

            try
            {
                comSave.CommandText = "INSERT INTO UnRegisterJobSeeker (Name,Experience,JobID,EmailAddress,ContactNo,City,State,Country,Resume,AppliedDate) VALUES (@Name,@Experience,@JobID,@EmailAddress,@ContactNo,@City,@State,@Country,@Resume,@AppliedDate)";

                comSave.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = txtName.Text.Trim();

                if (DropDownListExp.SelectedIndex == 0)
                {
                    comSave.Parameters.Add("@Experience", SqlDbType.VarChar, 50).Value = "";
                }
                else
                {
                    comSave.Parameters.Add("@Experience", SqlDbType.VarChar, 50).Value = DropDownListExp.Text.Trim();
                }

                comSave.Parameters.Add("@JobID", SqlDbType.VarChar, 50).Value        = Convert.ToString(Session["JobID"]);
                comSave.Parameters.Add("@EmailAddress", SqlDbType.VarChar, 50).Value = txtEmailAddress.Text.Trim();
                comSave.Parameters.Add("@ContactNo", SqlDbType.VarChar, 50).Value    = txtContactNo.Text.Trim();
                comSave.Parameters.Add("@City", SqlDbType.VarChar, 50).Value         = txtCity.Text.Trim();
                comSave.Parameters.Add("@State", SqlDbType.VarChar, 50).Value        = txtState.Text.Trim();
                comSave.Parameters.Add("@Country", SqlDbType.VarChar, 50).Value      = txtCountry.Text.Trim();

                comSave.Parameters.Add("@Resume", SqlDbType.VarChar, 50).Value      = Convert.ToString(ViewState["Resume"]);
                comSave.Parameters.Add("@AppliedDate", SqlDbType.VarChar, 50).Value = DateTime.Now.Date;

                comSave.Transaction = Trans1;
                comSave.Connection  = connection;
                comSave.ExecuteNonQuery();


                comCode.CommandText = "Update CodeGenerator set CurrentValue = CurrentValue + 1 where (Head = 'File')";
                comCode.Transaction = Trans1;
                comCode.Connection  = connection;
                comCode.ExecuteNonQuery();
                Trans1.Commit();
                lblResult.Text = "* You have successfully applied for selected job";
            }


            catch (Exception ex)
            {
                Trans1.Rollback();
                if (File.Exists(Server.MapPath(("~/Resume/" + Convert.ToString(ViewState["Resume"])))))
                {
                    File.Delete(Server.MapPath(("~/Resume/" + Convert.ToString(ViewState["Resume"]))));
                }
                lblResult.Text = "Error occurs";
            }
            finally
            {
                comSave.Dispose();
                comCode.Dispose();
                connection.Close();
            }
        }
Exemplo n.º 42
0
        public ActionResult customerorder(tbl_customer data, FormCollection data1, HttpPostedFileBase[] FILE_UPLOAD)
        {
            string commase      = "";
            var    multiplefile = Request.Form["FILE_UPLOAD"];

            if (data.FILE_UPLOAD != null)
            {
                Models.tbl_customer imgs = new tbl_customer();
                imgs.FILE_UPLOAD = data.FILE_UPLOAD;
                HttpFileCollectionBase file = Request.Files;
                for (int i = 0; i < file.Count; i++)
                {
                    HttpPostedFileBase Image = file[i];
                    var filename             = "";
                    if (Image != null)
                    {
                        filename = Path.GetFileName(Image.FileName);
                        var path3 = Path.Combine(Server.MapPath("~/UploadedFiles"), filename);
                        Image.SaveAs(path3);
                        data.FILE_UPLOAD = filename;
                        commase         += Image.FileName;
                        //conf.IMAGE = data.IMAGE;
                    }
                    commase += ",";
                }
            }
            //if (ModelState.IsValid)
            //{   //iterating through multiple file collection
            //    foreach (HttpPostedFileBase file in FILE_UPLOAD)
            //    {

            //        //Checking file is available to save.
            //        if (file != null)
            //        {
            //            var InputFileName = Path.GetFileName(file.FileName);
            //           var commaseparate = file.FileName;

            //            var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);
            //            //Save file to server folder



            //            file.SaveAs(ServerSavePath);

            //            //assigning file uploaded status to ViewBag for showing message to user.
            //            ViewBag.UploadStatus = FILE_UPLOAD.Count().ToString() + " files uploaded successfully.";
            //        }

            //    }
            //}
            //if(FILE_UPLOAD.Length > 0)
            //{
            //    HttpFileCollectionBase files = Request.Files;
            //    DataTable dt = new DataTable { Columns = { new DataColumn("path") } };
            //    for(int i=0; i< files.Count;i++)
            //    {
            //        HttpPostedFileBase file = files[i];
            //        string path = Server.MapPath("~") + "\\UploadedFiles\\" + file.FileName;
            //        dt.Rows.Add(file.FileName);
            //        file.SaveAs(path);

            //    }
            //    ViewData.Model = dt.AsEnumerable();
            //}

            data.DATE        = DateTime.Now;
            data.FILE_UPLOAD = commase;
            var abc = db.tbl_customer.Add(data);

            var name     = Request.Form["NAME"];
            var price    = Request.Form["PRICE"];
            var quantity = Request.Form["QUANTITY"];
            var amount   = Request.Form["AMOUNT"];

            string[]  name1     = name.Split(',');
            string[]  price1    = price.Split(',');
            string[]  quantity1 = quantity.Split(',');
            string[]  amount1   = amount.Split(',');
            tbl_order order     = new tbl_order();

            for (var i = 0; i < name1.Length; i++)
            {
                order.NAME        = name1[i];
                order.PRICE       = price1[i];
                order.QUANTITY    = quantity1[i];
                order.AMOUNT      = amount1[i];
                order.CUSTOMER_ID = data.ID;
                db.tbl_order.Add(order);
                db.SaveChanges();
            }

            return(Redirect("customerorder"));
        }
Exemplo n.º 43
0
 protected void btnAdd_Click(object sender, EventArgs e)
 {
     if (UpImage.HasFile)
     {
         FileInfo file = new FileInfo(UpImage.PostedFile.FileName);
         if (file.Extension.ToLower() != ".bmp" && file.Extension.ToLower() != ".jpg" && file.Extension.ToLower() != ".jpeg" && file.Extension.ToLower() != ".png" && file.Extension.ToLower() != ".gif")
         {
             Response.Write("<script>alert('上传的图片格式应为bmp/jpg/jpeg/png/gif格式');history.back(-1);</script>");
             return;
         }
         string filename = UpImage.PostedFile.FileName;
         filename = System.IO.Path.GetFileName(filename);
         //改文件名
         int    index    = filename.LastIndexOf(".");
         string lastName = filename.Substring(index, filename.Length - index);//获得文件后缀类型
         //新文件名称,以时间年月日时分秒作为文件名
         string newname = "BBSSubject" + DateTime.Now.ToString("yyyyMMddhhmmss") + lastName;
         double size    = UpImage.PostedFile.ContentLength;
         if (size >= 1024000)
         {
             Response.Write("<script>alert('添加失败!(图片容量请不要超过1MB)')</script>");
             return;
         }
         // 客户端文件路径 ,取得图片的文件名
         string webFilePath = Server.MapPath("/NewsImages/" + newname);
         if (!File.Exists(webFilePath))
         {
             UpImage.SaveAs(webFilePath); // 使用 SaveAs 方法保存文件
             System.Drawing.Image image = System.Drawing.Image.FromFile(webFilePath);
             float a = image.Width / image.Height;
             if (a > 5)
             {
                 image.Dispose();
                 File.Delete(webFilePath);
                 Response.Write("<script>alert('高宽比例不合适');</script>");
                 return;
             }
             System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image, 80, 80);
             string path = Server.MapPath("/IndexImages/" + newname);
             if (!File.Exists(path))
             {
                 bmp.Save(path);
             }
             image.Dispose();
             bmp.Dispose();
             File.Delete(webFilePath);
         }
         else
         {
             Response.Write("<script>alert('上传失败,请重试!')</script>");
             return;
         }
         string title    = Server.HtmlEncode(txtModuleName.Text.Trim());
         string describe = Server.HtmlEncode(Describe.Text.Trim());
         string sqlstr   = "insert into tb_Module "
                           + "(ModuleName,ModuleDate,ModuleImage,ModuleDescribe)"
                           + "values('" + title + "','" + DateTime.Now.ToString() + "','" + newname + "','" + describe + "')";
         if (sqlBind.DataCom(sqlstr))
         {
             Response.Write("<script lanuage=javascript>alert('添加成功');location='ManageMudole.aspx'</script>");
         }
     }
 }
Exemplo n.º 44
0
 public static void Call(Player p, ushort x, ushort y, ushort z)
 {
     events.ForEach(delegate(PlayerMoveEvent p1)
     {
         try
         {
             p1.method(p, x, y, z);
         }
         catch (Exception e) { Server.s.Log("The plugin " + p1.plugin.name + " errored when calling the PlayerMove Event!"); Server.ErrorLog(e); }
     });
 }
Exemplo n.º 45
0
    //读取第一级菜单,生成按钮
    protected string CreateMenu_1(object sender, EventArgs e)//读取第一级菜单,生成按钮
    {
        xmlpath = Server.MapPath("Xml/WebMenu.xml");
        string idkey;

        string[] role;
        string   UserName;

        //Application.Lock();
        //idkey = Application["ID_KEY"].ToString();
        //Application.UnLock();
        //if (Session["ID_KEY"] != null)
        if (Request.Cookies["ID_KEY"] != null)
        {
            idkey = Request.Cookies["ID_KEY"].Value.ToString();
            //UserName = Request.Cookies["UserName"].Value.ToString();
            UserName = bl.GetUserNameById(idkey, out errMsg);
            ArrayList list = bl.GetRolesByUserName(UserName, out errMsg);//得到角色名称
            role = (string[])list[0];
        }
        else
        {
            role = null;
        }

        //role = new  string[]{"1"};//测试
        xmldoc.Load(xmlpath);
        int c = xmldoc.ChildNodes[1].ChildNodes.Count;//获取首页下面第一级菜单的个数

        string[]   caption  = new string[c + 1];
        string[]   visible  = new string[c + 1];
        string[][] owner    = new string[c + 1][];
        string[]   FileName = new string[c + 1];
        caption[0]  = xmldoc.ChildNodes[1].Attributes["caption"].Value.ToString();
        visible[0]  = xmldoc.ChildNodes[1].Attributes["visible"].Value.ToString();
        owner[0]    = xmldoc.ChildNodes[1].Attributes["owner"].Value.ToString().TrimStart(',').TrimEnd(',').Split(',');
        FileName[0] = xmldoc.ChildNodes[1].Attributes["FileName"].Value.ToString();
        sb.Append("<td align=\"left\" valign=\"middle\">&nbsp;&nbsp;");
        if (visible[0] == "1")
        {
            if (IfRepeat(role, owner[0]) == true)
            {
                sb.AppendFormat("<a class=\"Text1\" href=\"javascript:gotoFile('{0}');\" onclick=\"SetColor(this)\">{1}</a>&nbsp;", FileName[0], caption[0]);
            }

            for (int i = 1; i <= c; i++)
            {
                caption[i]  = xmldoc.ChildNodes[1].ChildNodes[i - 1].Attributes["caption"].Value.ToString();
                visible[i]  = xmldoc.ChildNodes[1].ChildNodes[i - 1].Attributes["visible"].Value.ToString();
                owner[i]    = xmldoc.ChildNodes[1].ChildNodes[i - 1].Attributes["owner"].Value.ToString().TrimStart(',').TrimEnd(',').Split(',');
                FileName[i] = xmldoc.ChildNodes[1].ChildNodes[i - 1].Attributes["FileName"].Value.ToString();

                if (IfRepeat(role, owner[i]) == true)
                {
                    if (visible[i] == "1")
                    {
                        if (xmldoc.ChildNodes[1].ChildNodes[i - 1].ChildNodes.Count != 0)//如果该节点存在子节点,则生成菜单树
                        {
                            sb.AppendFormat("<a class=\"Text1\">|</a>&nbsp;<a runat=\"server\" runat=\"server\" Class=\"Text1\" onclick=\"SetColor(this)\"  href=\"javascript:gotoTree('{0}','{1}')\">{1}</a>&nbsp;", FileName[i], caption[i]);
                        }
                        else//如果该节点不在子节点,则点击直接跳转至该节点FileName属性所存储的文件链接
                        {
                            sb.AppendFormat("<a class=\"Text1\">|</a>&nbsp;<a runat=\"server\" runat=\"server\" Class=\"Text1\" onclick=\"SetColor(this)\" href=\"javascript:gotoFile('{0}');javascript:gotoTree('{0}','{1}')\">{1}</a>&nbsp;", FileName[i], caption[i]);
                        }
                    }
                }
            }
        }
        else if (visible[0] == "0")
        {
            sb.Append("<a class=\"Text1\">您缺少相关权限</a>");
        }
        sb.Append("</td>");

        return(sb.ToString());
    }
        protected void createPdfButton_Click(object sender, EventArgs e)
        {
            // Get the server IP and port
            String serverIP   = textBoxServerIP.Text;
            uint   serverPort = uint.Parse(textBoxServerPort.Text);

            // Create a PDF document
            Document pdfDocument = new Document(serverIP, serverPort);

            // Set optional service password
            if (textBoxServicePassword.Text.Length > 0)
            {
                pdfDocument.ServicePassword = textBoxServicePassword.Text;
            }

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // The titles font used to mark various sections of the PDF document
            PdfFont titleFont = new PdfFont("Times New Roman", 10, true);

            titleFont.Bold      = true;
            titleFont.Underline = true;

            // Create a PDF page in PDF document
            PdfPage pdfPage = pdfDocument.AddPage();

            // Text Elements Using Fonts Installed in System

            // Add section title
            TextElement titleTextElement = new TextElement(5, 5, "Text Elements Using Fonts Installed in System", titleFont);

            titleTextElement.ForeColor = RgbColor.DarkGreen;
            pdfPage.AddElement(titleTextElement);

            // Embed in PDF document a font with Normal style installed in system
            PdfFont embeddedSystemFontNormal = new PdfFont("Times New Roman", 10, true);

            // Add a text element using a font with Normal style installed in system
            TextElement embeddedSystemFontNormalTextElement = new TextElement(0, 0, "This text uses a font with Normal style installed in system", embeddedSystemFontNormal);

            pdfDocument.AddElement(embeddedSystemFontNormalTextElement, 5, 10);

            // Embed in PDF document a font with Bold style installed in system
            PdfFont embeddedSystemFontBold = new PdfFont("Times New Roman", 10, true);

            embeddedSystemFontBold.Bold = true;

            // Add a text element using a font with Bold style installed in system
            TextElement embeddedSystemFontBoldTextElement = new TextElement(0, 0, "This text uses a font with Bold style installed in system", embeddedSystemFontBold);

            pdfDocument.AddElement(embeddedSystemFontBoldTextElement, 3);

            // Embed in PDF document a font with Italic style installed in system
            PdfFont embeddedSystemFontItalic = new PdfFont("Times New Roman", 10, true);

            embeddedSystemFontItalic.Italic = true;

            // Add a text element using a font with Italic style installed in system
            TextElement embeddedSystemFontItalicTextElement = new TextElement(0, 0, "This text uses a font with Italic style installed in system", embeddedSystemFontItalic);

            pdfDocument.AddElement(embeddedSystemFontItalicTextElement, 3);

            // Text Elements Using Fonts From Local Files

            // Add section title
            titleTextElement           = new TextElement(0, 0, "Text Elements Using Fonts From Local Files", titleFont);
            titleTextElement.ForeColor = RgbColor.Navy;
            pdfDocument.AddElement(titleTextElement, -5, 15);

            // Embed a True Type font from a local file in PDF document
            PdfFont localTrueTypeFont = new PdfFont(Server.MapPath("~/DemoAppFiles/Input/Fonts/TrueType.ttf"), 10);

            // Add a text element using the local True Type font to PDF document
            TextElement localFontTtfTextElement = new TextElement(0, 0, "This text uses a True Type Font loaded from a local file", localTrueTypeFont);

            pdfDocument.AddElement(localFontTtfTextElement, 5, 10);

            // Embed an OpenType font with TrueType Outlines in PDF document
            PdfFont localOpenTypeTrueTypeFont = new PdfFont(Server.MapPath("~/DemoAppFiles/Input/Fonts/OpenTypeTrueType.otf"), 10);

            // Add a text element using the local OpenType font with TrueType Outlines to PDF document
            TextElement localOpenTypeTrueTypeFontTextElement = new TextElement(0, 0, "This text uses an Open Type Font with TrueType Outlines loaded from a local file", localOpenTypeTrueTypeFont);

            pdfDocument.AddElement(localOpenTypeTrueTypeFontTextElement);

            //  Embed an OpenType font with PostScript Outlines in PDF document
            PdfFont localOpenTypePostScriptFont = new PdfFont(Server.MapPath("~/DemoAppFiles/Input/Fonts/OpenTypePostScript.otf"), 10);

            // Add a text element using the local OpenType font with PostScript Outlines to PDF document
            TextElement localOpenTypePostScriptFontTextElement = new TextElement(0, 0, "This text uses an Open Type Font with PostScript Outlines loaded from a local file", localOpenTypePostScriptFont);

            pdfDocument.AddElement(localOpenTypePostScriptFontTextElement, 3);

            // Text Elements Using Standard PDF Fonts

            // Add section title
            titleTextElement           = new TextElement(0, 0, "Text Elements Using Standard PDF Fonts", titleFont);
            titleTextElement.ForeColor = RgbColor.DarkGreen;
            pdfDocument.AddElement(titleTextElement, -5, 10);

            // Create a standard PDF font with Normal style
            PdfFont standardPdfFontNormal = new PdfFont(StdFontBaseFamily.Helvetica, 10);

            // Add a text element using the standard PDF font with Normal style
            TextElement standardPdfFontNormalTextElement = new TextElement(0, 0, "This text uses a standard PDF font with Normal style", standardPdfFontNormal);

            pdfDocument.AddElement(standardPdfFontNormalTextElement, 5, 10);

            // Create a standard PDF font with Bold style
            PdfFont standardPdfFontBold = new PdfFont(StdFontBaseFamily.HelveticaBold, 10);

            // Add a text element using the standard PDF font with Bold style
            TextElement standardPdfFontBoldTextElement = new TextElement(0, 0, "This text uses a standard PDF font with Bold style", standardPdfFontBold);

            pdfDocument.AddElement(standardPdfFontBoldTextElement, 3);

            // Create a standard PDF font with Italic style
            PdfFont standardPdfFontItalic = new PdfFont(StdFontBaseFamily.HelveticaOblique, 10);

            // Add a text element using the standard PDF font with Italic style
            TextElement standardPdfFontItalicTextElement = new TextElement(0, 0, "This text uses a standard PDF font with Italic style", standardPdfFontItalic);

            pdfDocument.AddElement(standardPdfFontItalicTextElement, 3);

            // Add a text element that flows freely in width and height

            string text = System.IO.File.ReadAllText(Server.MapPath("~/DemoAppFiles/Input/Text_Files/Text_File.txt"));

            // Add section title
            titleTextElement           = new TextElement(0, 0, "Text Element that flows freely in width and height", titleFont);
            titleTextElement.ForeColor = RgbColor.DarkGreen;
            pdfDocument.AddElement(titleTextElement, -5, 10);

            // Add the text element
            TextElement freeWidthAndHeightTextElement = new TextElement(0, 0, text, embeddedSystemFontNormal);

            pdfDocument.AddElement(freeWidthAndHeightTextElement, 5, 10);

            // Add a text element with a given width that flows freely in height

            // Add section title
            titleTextElement           = new TextElement(0, 0, "Text Element with a given width that flows freely in height", titleFont);
            titleTextElement.ForeColor = RgbColor.Navy;
            pdfDocument.AddElement(titleTextElement, -5, 10);

            // Add the text element
            TextElement freeHeightTextElement = new TextElement(0, 0, 400, text, embeddedSystemFontNormal);

            pdfDocument.AddElement(freeHeightTextElement, 5, 10);

            // Add a text element with a given width and height

            // Add section title
            titleTextElement           = new TextElement(0, 0, "Text Element with a given width and height", titleFont);
            titleTextElement.ForeColor = RgbColor.DarkGreen;
            pdfDocument.AddElement(titleTextElement, -5, 10);

            // Add the text element
            TextElement boundedTextElement = new TextElement(0, 0, 400, 50, text, embeddedSystemFontNormal);

            pdfDocument.AddElement(boundedTextElement, 5, 10);

            // Add a text element that flows freely on next PDF page

            // Add section title
            titleTextElement           = new TextElement(0, 0, "Text Element that flows freely on multiple PDF pages", titleFont);
            titleTextElement.ForeColor = RgbColor.Navy;
            pdfDocument.AddElement(titleTextElement, -5, 10);

            // Add the text element
            string      multiPageText        = System.IO.File.ReadAllText(Server.MapPath("~/DemoAppFiles/Input/Text_Files/Large_Text_File.txt"));
            TextElement multiPageTextElement = new TextElement(0, 0, 575, multiPageText, embeddedSystemFontNormal);

            multiPageTextElement.BackColor = RgbColor.WhiteSmoke;
            pdfDocument.AddElement(multiPageTextElement, 5, 10);

            // Add a line at the bottom of the multipage text element

            LineElement bottomLine = new LineElement(0, 0, 100, 0);

            pdfDocument.AddElement(bottomLine, 0, 1);

            pdfPage = pdfDocument.AddPage();

            // Text Elements with Vertical Text

            // Add section title
            titleTextElement           = new TextElement(0, 0, "Vertical Text", titleFont);
            titleTextElement.ForeColor = RgbColor.Navy;
            pdfPage.AddElement(titleTextElement);

            // Add a top to bottom vertical text
            string topBottomText = "This is a Top to Bottom Vertical Text";

            TextElement topBottomVerticalTextElement = new TextElement(0, 0, topBottomText, embeddedSystemFontNormal);

            topBottomVerticalTextElement.Translate(25, 50);
            topBottomVerticalTextElement.Rotate(90);
            pdfDocument.AddElement(topBottomVerticalTextElement);

            pdfPage = pdfDocument.AddPage();

            // Add a bottom to top vertical text
            string bottomTopText      = "This is a Bottom to Top Vertical Text";
            float  bottomTopTextWidth = 200;

            TextElement bottomTopVerticalTextElement = new TextElement(0, 0, bottomTopText, embeddedSystemFontNormal);

            bottomTopVerticalTextElement.Translate(0, bottomTopTextWidth);
            bottomTopVerticalTextElement.Rotate(-90);
            pdfPage.AddElement(bottomTopVerticalTextElement);

            // Add a text stamp to a PDF document

            // Create a PDF font
            PdfFont stampPdfFont = new PdfFont("Times New Roman", 24, true);
            // The stamp text
            string stampText = String.Format("Text Stamp {0}", DateTime.Now.ToString("d"));
            // Measure the text
            float   textWidth = 100;
            PdfPage page      = pdfDocument.AddPage();
            // Get the PDF page drawable area width and height
            float pdfPageWidth  = page.PageSize.Width;
            float pdfPageHeight = page.PageSize.Height;

            // Calculate the PDF page diagonal
            float pdfPageDiagonal = (float)Math.Sqrt(pdfPageWidth * pdfPageWidth + pdfPageHeight * pdfPageHeight);

            // The text location on PDF page diagonal
            float xStampLocation = (pdfPageDiagonal - textWidth) / 2;

            // Create the stamp as a rotated text element
            TextElement stampTextElement = new TextElement(xStampLocation, 0, stampText, stampPdfFont);

            stampTextElement.ForeColor = RgbColor.Coral;
            stampTextElement.Rotate((float)(Math.Atan(pdfPageHeight / pdfPageWidth) * (180 / Math.PI)));
            stampTextElement.Opacity = 75;

            // Add the stamp to PDF page
            page.AddElement(stampTextElement);

            // Save the PDF document in a memory buffer
            byte[] outPdfBuffer = pdfDocument.Save();

            // Send the PDF as response to browser

            // Set response content type
            Response.AddHeader("Content-Type", "application/pdf");

            // Instruct the browser to open the PDF file as an attachment or inline
            Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Text_Elements.pdf; size={0}", outPdfBuffer.Length.ToString()));

            // Write the PDF document buffer to HTTP response
            Response.BinaryWrite(outPdfBuffer);

            // End the HTTP response and stop the current page processing
            Response.End();
        }
Exemplo n.º 47
0
        public void PrintBill()
        {
            try
            {
                int UserId = ddlUser.SelectedIndex;
                List <ProductInvoice_Master> _bill = ProductInvoice_MasterCollection.GetAll().FindAll(x => x.BILL_ID == billid);
                #region Company
                string CompanyName    = USERPROFILEMASTER.GetByRegistration_ID(1).First_Name;
                string CompanyAddress = USERPROFILEMASTER.GetByRegistration_ID(1).Address;
                string CompanyState   = USERPROFILEMASTER.GetByRegistration_ID(1).StateName;
                string CompanyCity    = USERPROFILEMASTER.GetByRegistration_ID(1).CityName;
                string ZipCode        = USERPROFILEMASTER.GetByRegistration_ID(1).ZipCode;
                string CompanyGST     = USERPROFILEMASTER.GetByRegistration_ID(1).GstinVerified;
                string CompanyContact = USERPROFILEMASTER.GetByRegistration_ID(1).ContactNumber;
                #endregion
                #region Seller
                string ShipName  = USERPROFILEMASTER.GetByRegistration_ID(UserId).First_Name + " " + USERPROFILEMASTER.GetByRegistration_ID(UserId).Last_Name;
                string ShipAdd1  = USERPROFILEMASTER.GetByRegistration_ID(UserId).Address;
                string ShipAdd2  = USERPROFILEMASTER.GetByRegistration_ID(UserId).AddressLine2;
                string ShipCity  = USERPROFILEMASTER.GetByRegistration_ID(UserId).CityName;
                string ShipState = USERPROFILEMASTER.GetByRegistration_ID(UserId).StateName;
                string ShipZip   = USERPROFILEMASTER.GetByRegistration_ID(UserId).ZipCode;
                string Contry    = USERPROFILEMASTER.GetByRegistration_ID(UserId).COUNTRY;

                string BillName       = USERPROFILEMASTER.GetByRegistration_ID(UserId).First_Name + " " + USERPROFILEMASTER.GetByRegistration_ID(UserId).Last_Name;
                string PermanentAdd1  = USERPROFILEMASTER.GetByRegistration_ID(UserId).ShippingAddress;
                string PermanentAdd2  = USERPROFILEMASTER.GetByRegistration_ID(UserId).ShippingAddressLine2;
                string PermanentCity  = USERPROFILEMASTER.GetByRegistration_ID(UserId).ShipCityName;
                string PermanentState = USERPROFILEMASTER.GetByRegistration_ID(UserId).ShippStateName;
                string PermanentZip   = USERPROFILEMASTER.GetByRegistration_ID(UserId).ShippingZip;
                string Gstin          = USERPROFILEMASTER.GetByRegistration_ID(UserId).GstinVerified;
                #endregion
                #region BillDetail
                System.Guid guid      = System.Guid.NewGuid();
                String      id        = guid.ToString();
                string      OrderId   = id;
                DateTime    dt        = System.DateTime.Today;
                string      InvoiNo   = "";
                string      InvoiDate = dt.ToString();
                string      Phone     = USERPROFILEMASTER.GetByRegistration_ID(UserId).ContactNumber;
                string      Email     = USERPROFILEMASTER.GetByRegistration_ID(UserId).Email;
                #endregion
                string  BillNo = OrderBillMaster.GetByOrderBILL_ID(billid).BILLNO;
                decimal totamt = Math.Round(ProductBill_Master.GetByBILL_ID(billid).TOTAL, 0);
                var     values = totamt.ToString(CultureInfo.InvariantCulture).Split('.');
                Int64   rup    = Convert.ToInt64(values[0]);
                Int64   paise  = 0;
                if (values.Length == 2)
                {
                    paise = Convert.ToInt64(values[1]);
                }
                string rupee = string.Empty;
                string pa    = string.Empty;
                if (paise != 0)
                {
                    pa    = Rupees(paise) + "Paise Only";
                    rupee = Rupees(rup) + "Rupees and " + pa;
                }
                else
                {
                    rupee = Rupees(rup) + "Rupees Only";
                }
                ReportViewer1.ProcessingMode = ProcessingMode.Local;
                this.ReportViewer1.LocalReport.EnableExternalImages = true;
                ReportViewer1.LocalReport.ReportPath = Server.MapPath("/Report/PickUpOrder.rdlc");
                ReportDataSource datasource = new ReportDataSource("BillGenrate", _bill);
                //ReportParameter[] rpt = new ReportParameter[28];
                //rpt[0] = new ReportParameter("CompanyName", CompanyName);
                //rpt[1] = new ReportParameter("CompanyAddress", CompanyAddress);
                //rpt[2] = new ReportParameter("CompanyState", CompanyState);
                //rpt[3] = new ReportParameter("CompanyCity", CompanyCity);
                //rpt[4] = new ReportParameter("ZipCode", ZipCode);
                //rpt[5] = new ReportParameter("CompanyGST", CompanyGST);
                //rpt[6] = new ReportParameter("CompanyContact", CompanyContact);
                //rpt[7] = new ReportParameter("ShipName", ShipName);
                //rpt[8] = new ReportParameter("ShipAdd1", ShipAdd1);
                //rpt[9] = new ReportParameter("ShipAdd2", ShipAdd2);
                //rpt[10] = new ReportParameter("ShipCity", ShipCity);
                //rpt[11] = new ReportParameter("ShipState", ShipState);
                //rpt[12] = new ReportParameter("ShipZip", ShipZip);
                //rpt[13] = new ReportParameter("Contry", Contry);
                //rpt[14] = new ReportParameter("BillName", BillName);
                //rpt[15] = new ReportParameter("PermanentAdd1", PermanentAdd1);
                //rpt[16] = new ReportParameter("PermanentAdd2", PermanentAdd2);
                //rpt[17] = new ReportParameter("PermanentCity", PermanentCity);
                //rpt[18] = new ReportParameter("PermanentState", PermanentState);
                //rpt[19] = new ReportParameter("PermanentZip", PermanentZip);
                //rpt[20] = new ReportParameter("Gstin", Gstin);
                //rpt[21] = new ReportParameter("OrderId", OrderId);
                //rpt[22] = new ReportParameter("InvoiNo", InvoiNo);
                //rpt[23] = new ReportParameter("InvoiDate", InvoiDate);
                //rpt[24] = new ReportParameter("Phone", Phone);
                //rpt[25] = new ReportParameter("Email", Email);
                //rpt[26] = new ReportParameter("TotalAmountWord", rupee);
                //rpt[27] = new ReportParameter("@PaymentMod", "Wallet");
                //this.ReportViewer1.LocalReport.SetParameters(rpt);
                this.ReportViewer1.LocalReport.DataSources.Clear();
                this.ReportViewer1.LocalReport.DataSources.Add(datasource);
                this.ReportViewer1.LocalReport.Refresh();
            }
            catch (Exception ex)
            { }
        }
Exemplo n.º 48
0
    //下载存储菜单的XML文件
    protected void DownLoadXml(object sender, EventArgs e)//下载XML
    {
        bool   ret    = true;
        string DBtype = bl.GetDBtype();

        if (DBtype == "SQL")//从SQLSERVER数据库下载菜单XML文件
        {
            //try
            //{
            //    SqlConnection sqlconn = SAC.sqlHelper.DBsql.GetConnection();
            //    string sqlstr = "select * from T_SYS_MENU where T_XMLID='Webmenu'";
            //    SqlCommand sqlcmd = new SqlCommand(sqlstr, sqlconn);
            //    SqlDataReader sqlreader = sqlcmd.ExecuteReader();
            //    FileName = xmlpath;
            //    if (!sqlreader.Read())
            //    {
            //        FileName = "";
            //    }
            //    else
            //    {
            //        byte[] bytes = (byte[])sqlreader["B_XML"];
            //        FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
            //        fs.Write(bytes, 0, bytes.Length);
            //        fs.Flush();
            //        fs.Close();
            //    }
            //    sqlreader.Close();
            //    sqlconn.Close();
            //}
            //catch (Exception ce)
            //{
            //    errMsg = ce.Message;
            //    ret = false;
            //}
        }
        else//从DB2数据库下载菜单XML文件
        {
            try
            {
                string          connstr = bl.GetConnstr(out errMsg).ToString();
                OleDbConnection db2conn = new OleDbConnection(connstr);
                string          sqlstr  = "select * from T_SYS_MENU where T_XMLID='Webmenu'";
                OleDbCommand    db2cmd  = new OleDbCommand(sqlstr, db2conn);
                db2conn.Open();
                OleDbDataReader db2reader = db2cmd.ExecuteReader();
                xmlpath  = Server.MapPath("Xml/WebMenu.xml");
                FileName = xmlpath;
                if (!db2reader.Read())
                {
                    FileName = "";
                }
                else
                {
                    byte[]     bytes = (byte[])db2reader["B_XML"];
                    FileStream fs    = new FileStream(FileName, FileMode.Create, FileAccess.Write);
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Flush();
                    fs.Close();
                }
                db2reader.Close();
                db2conn.Close();
            }
            catch (Exception ce)
            {
                errMsg = ce.Message;
                ret    = false;
            }
        }
    }
Exemplo n.º 49
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            int id = model.Id;
            using (Db db = new Db())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }

            model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id.ToString() + "/Gallery/Thumbs"))
                   .Select(fn => Path.GetFileName(fn));

            if (!ModelState.IsValid)
            {
                return View(model);
            }

            using (Db db = new Db())
            {
                if(db.Products.Where(x=> x.Id!=id).Any(x=>x.Name==model.Name))
                {
                    ModelState.AddModelError("", "That product name is taken");
                    return View(model);
                }
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");

                ProductDTO dto = db.Products.Find(id);
                dto.Name = model.Name;
                dto.Slug = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price = model.Price;
                dto.CategoryId = model.CategoryId;
                dto.ImageName = model.ImageName;

                CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = catDto.Name;

                db.SaveChanges();
            }

            TempData["SM"] = "You have edited the product";

            #region Image Upload

            if(file!=null&&file.ContentLength>0)
            {
                string ext = file.ContentType.ToLower();
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not uploaded - wrong image extension");
                    }
                    return View(model);
                }

                var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));

                string[] paths = new string[] {
                 Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()),
                 Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()+ "\\Thumbs")
                };
                foreach (var path in paths)
                {
                    DirectoryInfo di = new DirectoryInfo(path);
                    foreach(var files in di.GetFiles())
                    {
                        files.Delete();
                    }
                }


                string imageName = file.FileName;

                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;
                    db.SaveChanges();
                }

                string[] pathWithFiles = new string[] {
                    string.Format($"{paths[0]}\\{imageName}"),
                    string.Format($"{paths[1]}\\{imageName}")
                };

                file.SaveAs(pathWithFiles[0]);

                WebImage wi = new WebImage(file.InputStream);
                wi.Resize(200, 200).Crop(1, 1);
                wi.Save(pathWithFiles[1]);

            }

            #endregion

            return RedirectToAction("EditProduct");


        }
Exemplo n.º 50
0
 protected void logoutButton_Click(object sender, EventArgs e)
 {
     Session["UserLogged"] = null;
     Server.Transfer("../Account/Login.aspx", true);
 }
 protected void UploadButton_Click(object sender, EventArgs e)
 {
     if (FileUploader.HasFile && !string.IsNullOrWhiteSpace(KeyWordTextBox.Text))
     {
         try
         {
             if (FileUploader.FileName.Split('.')[FileUploader.FileName.Split('.').Length - 1] == "txt")
             {
                 FileUploader.PostedFile.SaveAs(Server.MapPath("~/Data/") + FileUploader.FileName);
                 string s = File.ReadAllText(Server.MapPath("~/Data/") + FileUploader.FileName);
                 if (s.Contains((char)65533))
                 {
                     s = ChangeEncoding();
                 }
                 BeforeTextBox.Text = s;
                 Encryptor encryptor = new Encryptor(s, KeyWordTextBox.Text);
                 if (VigenereModeRadioButtonList.SelectedValue == "TrueVigenere")
                 {
                     EncryptText = encryptor.EncryptText(true);
                 }
                 else
                 {
                     EncryptText = encryptor.EncryptText(false);
                 }
                 AfterTextBox.Text = EncryptText;
             }
             else if (FileUploader.FileName.Split('.')[FileUploader.FileName.Split('.').Length - 1] == "docx")
             {
                 FileUploader.PostedFile.SaveAs(Server.MapPath("~/Data/") + FileUploader.FileName);
                 var s = "";
                 using (var wordDocument = WordprocessingDocument.Open(Server.MapPath("~/Data/") + FileUploader.FileName as string, false))
                 {
                     s = wordDocument.MainDocumentPart.Document.Body.InnerText;
                 }
                 BeforeTextBox.Text = s;
                 Encryptor encryptor = new Encryptor(s, KeyWordTextBox.Text);
                 if (VigenereModeRadioButtonList.SelectedValue == "TrueVigenere")
                 {
                     EncryptText = encryptor.EncryptText(true);
                 }
                 else
                 {
                     EncryptText = encryptor.EncryptText(false);
                 }
                 AfterTextBox.Text = EncryptText;
             }
         }
         catch (IndexOutOfRangeException)
         {
             Response.Write("Кодовое слово должно быть введено на кириллице");
         }
         finally
         {
             File.Delete(Server.MapPath("~/Data/") + FileUploader.FileName);
         }
     }
     else
     {
         Response.Write("Файл не выбран, либо не введено кодовое слово");
     }
 }
Exemplo n.º 52
0
        /// <summary>
        /// Retrieve all Buggs matching the search criteria.
        /// </summary>
        /// <param name="FormData">The incoming form of search criteria from the client.</param>
        /// <returns>A view to display the filtered Buggs.</returns>
        public CSV_ViewModel GetResults(FormHelper FormData)
        {
            using (FAutoScopedLogTimer LogTimer = new FAutoScopedLogTimer(this.GetType().ToString()))
            {
                var anonymousGroup        = _unitOfWork.UserGroupRepository.First(data => data.Name == "Anonymous");
                var anonymousGroupId      = anonymousGroup.Id;
                var anonumousIDs          = new HashSet <int>(anonymousGroup.Users.Select(data => data.Id));
                var anonymousID           = anonumousIDs.First();
                var userNamesForUserGroup = new HashSet <string>(anonymousGroup.Users.Select(data => data.UserName));

                // Enable to narrow results and improve debugging performance.
                //FormData.DateFrom = FormData.DateTo.AddDays( -1 );
                //FormData.DateTo = FormData.DateTo.AddDays( 1 );

                var FilteringQueryJoin = _unitOfWork.CrashRepository
                                         .ListAll()
                                         .Where(c => c.EpicAccountId != "")
                                         // Only crashes and asserts
                                         .Where(c => c.CrashType == 1 || c.CrashType == 2)
                                         // Only anonymous user
                                         .Where(c => c.UserNameId == anonymousID)
                                         // Filter be date
                                         .Where(c => c.TimeOfCrash > FormData.DateFrom && c.TimeOfCrash < FormData.DateTo)
                                         .Select
                                         (
                    c => new
                {
                    GameName     = c.GameName,
                    TimeOfCrash  = c.TimeOfCrash.Value,
                    BuiltFromCL  = c.ChangeListVersion,
                    PlatformName = c.PlatformName,
                    EngineMode   = c.EngineMode,
                    MachineId    = c.ComputerName,
                    Module       = c.Module,
                    BuildVersion = c.BuildVersion,
                    Jira         = c.Jira,
                    Branch       = c.Branch,
                    CrashType    = c.CrashType,
                    EpicId       = c.EpicAccountId,
                    BuggId       = c.Buggs.First().Id
                }
                                         );

                var FilteringQueryCrashes = _unitOfWork.CrashRepository
                                            .ListAll()
                                            .Where(c => c.EpicAccountId != "")
                                            // Only crashes and asserts
                                            .Where(c => c.CrashType == 1 || c.CrashType == 2)
                                            // Only anonymous user
                                            .Where(c => c.UserNameId == anonymousID);

                //Server timeout
                int TotalCrashes = _unitOfWork.CrashRepository.ListAll().Count();

                int TotalCrashesYearToDate = _unitOfWork.CrashRepository
                                             .ListAll().Count(c => c.TimeOfCrash > new DateTime(DateTime.UtcNow.Year, 1, 1));

                var CrashesFilteredWithDateQuery = FilteringQueryCrashes
                                                   // Filter be date
                                                   .Where(c => c.TimeOfCrash > FormData.DateFrom && c.TimeOfCrash < FormData.DateTo);

                int CrashesFilteredWithDate = CrashesFilteredWithDateQuery
                                              .Count();

                int CrashesYearToDateFiltered = FilteringQueryCrashes.Count(c => c.TimeOfCrash > new DateTime(DateTime.UtcNow.Year, 1, 1));

                //DB server timeout
                int AffectedUsersFiltered = FilteringQueryCrashes.Select(c => c.EpicAccountId).Distinct().Count();

                //DB server time out
                int UniqueCrashesFiltered = FilteringQueryCrashes.Select(c => c.Pattern).Count();

                int NumCrashes = FilteringQueryJoin.Count();

                // Export data to the file.
                string CSVPathname = Path.Combine(Settings.Default.CrashReporterCSV, DateTime.UtcNow.ToString("yyyy-MM-dd.HH-mm-ss"));
                CSVPathname += string
                               .Format("__[{0}---{1}]__{2}",
                                       FormData.DateFrom.ToString("yyyy-MM-dd"),
                                       FormData.DateTo.ToString("yyyy-MM-dd"),
                                       NumCrashes)
                               + ".csv";

                string ServerPath = Server.MapPath(CSVPathname);
                var    CSVFile    = new StreamWriter(ServerPath, true, Encoding.UTF8);

                using (FAutoScopedLogTimer ExportToCSVTimer = new FAutoScopedLogTimer("ExportToCSV"))
                {
                    var RowType = FilteringQueryJoin.FirstOrDefault().GetType();

                    string AllProperties = "";
                    foreach (var Property in RowType.GetProperties())
                    {
                        AllProperties += Property.Name;
                        AllProperties += "; ";
                    }

                    // Write header
                    CSVFile.WriteLine(AllProperties);

                    foreach (var Row in FilteringQueryJoin)
                    {
                        var BVParts = Row.BuildVersion.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                        if (BVParts.Length > 2 && BVParts[0] != "0")
                        {
                            string CleanEngineVersion = string.Format("{0}.{1}.{2}", BVParts[0], BVParts[1], BVParts[2]);

                            string[] RowProperties = new string[]
                            {
                                Row.GameName,
                                Row.TimeOfCrash.ToString(),
                                Row.BuiltFromCL,
                                Row.PlatformName,
                                Row.EngineMode,
                                Row.MachineId,
                                Row.Module,
                                CleanEngineVersion,
                                Row.Jira,
                                Row.Branch,
                                Row.CrashType == 1 ? "Crash" : "Assert",
                                Row.EpicId,
                                Row.BuggId.ToString()
                            };

                            string JoinedLine = string.Join("; ", RowProperties);
                            JoinedLine += "; ";

                            CSVFile.WriteLine(JoinedLine);
                        }
                    }

                    CSVFile.Flush();
                    CSVFile.Close();
                    CSVFile = null;
                }

                List <FCSVRow> CSVRows = FilteringQueryJoin
                                         .OrderByDescending(X => X.TimeOfCrash)
                                         .Take(32)
                                         .Select(c => new FCSVRow
                {
                    GameName     = c.GameName,
                    TimeOfCrash  = c.TimeOfCrash,
                    BuiltFromCL  = c.BuiltFromCL,
                    PlatformName = c.PlatformName,
                    EngineMode   = c.EngineMode,
                    MachineId    = c.MachineId,
                    Module       = c.Module,
                    BuildVersion = c.BuildVersion,
                    Jira         = c.Jira,
                    Branch       = c.Branch,
                    CrashType    = c.CrashType,
                    EpicId       = c.EpicId,
                    BuggId       = c.BuggId,
                })
                                         .ToList();

                return(new CSV_ViewModel()
                {
                    CSVRows = CSVRows,
                    CSVPathname = CSVPathname,
                    DateFrom = (long)(FormData.DateFrom - CrashesViewModel.Epoch).TotalMilliseconds,
                    DateTo = (long)(FormData.DateTo - CrashesViewModel.Epoch).TotalMilliseconds,
                    DateTimeFrom = FormData.DateFrom,
                    DateTimeTo = FormData.DateTo,
                    AffectedUsersFiltered = AffectedUsersFiltered,
                    UniqueCrashesFiltered = UniqueCrashesFiltered,
                    CrashesFilteredWithDate = CrashesFilteredWithDate,
                    TotalCrashes = TotalCrashes,
                    TotalCrashesYearToDate = TotalCrashesYearToDate,
                });
            }
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder();

            DevExpress.Web.ASPxWebControl.CallbackError += Application_Error;
            DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension.RegisterExtensionGlobal(new MyReportStorage(Server.MapPath("/Reports")));
        }
Exemplo n.º 54
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                }

                return View(model);
            }

            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "This product name is taken");
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return View(model);
                }
            }

            int id;

            using (Db db = new Db())
            {
                ProductDTO dto = new ProductDTO();

                dto.Name = model.Name;
                dto.Slug = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price = model.Price;
                dto.CategoryId = model.CategoryId;
                CategoryDTO categoryDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = categoryDTO.Name ?? "";

                db.Products.Add(dto);
                db.SaveChanges();
                id = dto.Id;
            }
            TempData["SM"] = "You have added a product";
            #region Upload Image
            var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));

            string[] paths = new string[] {
                 Path.Combine(originalDirectory.ToString(), "Products"),
                 Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()),
                 Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()+ "\\Thumbs"),
                 Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"),
                 Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs")
            };
            foreach (var path in paths)
            {
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
            }

            if (file != null && file.ContentLength > 0)
            {
                string ext = file.ContentType.ToLower();
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not uploaded - wrong image extension");
                    }
                    return View(model);
                }


                string imageName = file.FileName;

                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;
                    db.SaveChanges();
                }

                string[] pathWithFiles = new string[] {
                    string.Format($"{paths[1]}\\{imageName}"),
                    string.Format($"{paths[2]}\\{imageName}")
                };

                file.SaveAs(pathWithFiles[0]);

                WebImage wi = new WebImage(file.InputStream);
                wi.Resize(200, 200).Crop(1,1);
                wi.Save(pathWithFiles[1]);
            }
            #endregion

            
            return RedirectToAction("AddProduct");
        }
Exemplo n.º 55
0
    protected void Page_Load(object sender, EventArgs e)
    {
        this.CurrentMaster.DisplaySiteSelectorPanel = true;

        this.lblInfo.Visible = false;
        this.lblError.Visible = false;

        // Get page template id from url
        templateId = ValidationHelper.GetInteger(Request.QueryString["templateid"], 0);
        PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateId);

        string templateName = this.txtName.Text.Trim();
        if (templateName == "")
        {
            if (radMaster.Checked)
            {
                templateName = "MainMenu";
            }
            else
            {
                templateName = "Template";
            }

            if (pti != null)
            {
                 templateName = ValidationHelper.GetIdentifier(pti.DisplayName);
            }

            this.txtName.Text = templateName;
        }

        // Set site selector        
        siteSelector.AllowAll = false;
        siteSelector.UseCodeNameForSelection = true;


        if (!RequestHelper.IsPostBack())
        {
            selectedSite = CMSContext.CurrentSiteName;
            siteSelector.Value = selectedSite;
        }
        else
        {
            selectedSite = ValidationHelper.GetString(siteSelector.Value, String.Empty);
        }

        string className = "CMSTemplates_" + selectedSite + "_" + templateName;
        fileName = templateName;

        lblCodeInfo.Text = GetString("pagetemplate_aspx.info");
        lblCodeBehindInfo.Text = GetString("pagetemplate_aspx.codebehindinfo");

        lblName.Text = GetString("pagetemplate_aspx.name");
        lblMaster.Text = GetString("pagetemplate_aspx.mastername");
        btnSave.Text = GetString("pagetemplate_aspx.save");
        btnRefresh.Text = GetString("pagetemplate_aspx.refresh");

        radSlave.Text = GetString("pagetemplate_aspx.slave");
        radMaster.Text = GetString("pagetemplate_aspx.master");
        radTemplate.Text = GetString("pagetemplate_aspx.template");
        radTemplateOnly.Text = GetString("pagetemplate_aspx.templateonly");

        this.plcMasterTemplate.Visible = this.radSlave.Checked;

        if (pti != null)
        {
            string codeBehind = "";
            string registerCode = "";
            string code = PortalHelper.GetPageTemplateASPXCode(pti, out registerCode);

            if (this.radTemplateOnly.Checked)
            {
                code = registerCode + code;
            }
            else if (this.radSlave.Checked)
            {
                fileName += ".aspx";

                codeBehind = File.ReadAllText(Server.MapPath("~/CMSModules/PortalEngine/UI/PageTemplates/ASPX/ChildTemplate.aspx.cs"));
                codeBehind = codeBehind.Replace("PageTemplates_ChildTemplate", className);

                string pageCode = File.ReadAllText(Server.MapPath("~/CMSModules/PortalEngine/UI/PageTemplates/ASPX/ChildTemplate.aspx"));
                pageCode = pageCode.Replace(" Inherits=\"PageTemplates_ChildTemplate\"", " Inherits=\"" + className + "\"");
                pageCode = pageCode.Replace(" CodeFile=\"ChildTemplate.aspx.cs\"", " CodeFile=\"" + fileName + ".cs\"");

                string master = "";
                if (this.txtMaster.Text.Trim() != "")
                {
                    master = " MasterPageFile=\"" + this.txtMaster.Text.Trim() + ".master\"";
                }
                pageCode = pageCode.Replace(" MasterPageFile=\"Template.master\"", master);

                pageCode = pageCode.Replace("<%--REGISTER--%>", registerCode);

                pageCode = pageCode.Replace("<%--CONTENT--%>", code);

                code = pageCode;
            }
            else if (this.radMaster.Checked)
            {
                fileName += ".master";

                codeBehind = File.ReadAllText(Server.MapPath("~/CMSModules/PortalEngine/UI/PageTemplates/ASPX/Template.master.cs"));
                codeBehind = codeBehind.Replace("PageTemplates_MasterTemplate", className);

                string pageCode = File.ReadAllText(Server.MapPath("~/CMSModules/PortalEngine/UI/PageTemplates/ASPX/Template.master"));
                pageCode = pageCode.Replace(" Inherits=\"PageTemplates_MasterTemplate\"", " Inherits=\"" + className + "\"");
                pageCode = pageCode.Replace(" CodeFile=\"Template.master.cs\"", " CodeFile=\"" + fileName + ".cs\"");

                pageCode = pageCode.Replace("<%@ Register Assembly=\"CMS.Controls\" Namespace=\"CMS.Controls\" TagPrefix=\"cc1\" %>", "");
                pageCode = pageCode.Replace("<%--REGISTER--%>", registerCode);

                code = code.Replace("<%--CONTENT--%>", "<asp:ContentPlaceHolder ID=\"plcMain\" runat=\"server\"></asp:ContentPlaceHolder>");

                pageCode = pageCode.Replace("<%--CONTENT--%>", code);

                code = pageCode;
            }
            else if (this.radTemplate.Checked)
            {
                fileName += ".aspx";

                codeBehind = File.ReadAllText(Server.MapPath("~/CMSModules/PortalEngine/UI/PageTemplates/ASPX/Template.aspx.cs"));
                codeBehind = codeBehind.Replace("PageTemplates_Template", className);

                string pageCode = File.ReadAllText(Server.MapPath("~/CMSModules/PortalEngine/UI/PageTemplates/ASPX/Template.aspx"));
                pageCode = pageCode.Replace("Inherits=\"PageTemplates_Template\"", "Inherits=\"" + className + "\"");
                pageCode = pageCode.Replace(" CodeFile=\"Template.aspx.cs\"", " CodeFile=\"" + fileName + ".cs\"");

                pageCode = pageCode.Replace("<%@ Register Assembly=\"CMS.Controls\" Namespace=\"CMS.Controls\" TagPrefix=\"cc1\" %>", "");
                pageCode = pageCode.Replace("<%--REGISTER--%>", registerCode);

                pageCode = pageCode.Replace("<%--CONTENT--%>", code);

                code = pageCode;
            }

            this.txtCode.Text = HTMLHelper.ReformatHTML(code);
            this.txtCodeBehind.Text = codeBehind;
        }

        lblSaveInfo.Text = String.Format(GetString("pagetemplate_aspx.saveinfo"), "~/CMSTemplates/" + selectedSite + "/" + fileName);
    }
Exemplo n.º 56
0
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        RadUploadContext upContext = RadUploadContext.Current;
        string           dir       = Server.MapPath("~/App_Uploads_Img/");

        if (RadUpload1.UploadedFiles.Count > 0)
        {
            foreach (Telerik.Web.UI.UploadedFile file in RadUpload1.UploadedFiles)
            {
                if ((DropDownList1I.SelectedIndex == 0) && (tbDirectoryImage.Text.Length == 0))
                {
                    Session["cat"]   = null;
                    Session["Files"] = null;
                    TabPanel3.Focus();
                }
                else if ((DropDownList1I.SelectedIndex == 0) && (tbDirectoryImage.Text.Length > 0))
                {
                    string width  = ResizeWidth;
                    string height = ResizeHeight;
                    string suffix = ResizeSuffix;
                    Directory.CreateDirectory(dir + tbDirectoryImage.Text);
                    string name = file.GetName();



                    if (ResizeImage == true)
                    {
                        string path         = tbDirectoryImage.Text + "/";
                        string physicalpath = Server.MapPath("~/App_Uploads_Img/" + tbDirectoryImage.Text + "/");


                        // Save temporary file, we'll use this for our resizing then delete it after
                        file.SaveAs(physicalpath + name, true);

                        // Begin resize function
                        resize(name, path, physicalpath, width, height, suffix);
                    }
                    else
                    {
                        string physicalpath = Server.MapPath("~/App_Uploads_Img/" + tbDirectoryImage.Text + "/");
                        file.SaveAs(physicalpath + name, true);
                    }
                    Session["cat"] = tbDirectoryImage.Text;
                    string sFileName = file.GetName().ToLower();
                    string na        = sFileName.Substring(0, sFileName.LastIndexOf("."));
                    string format    = sFileName.Substring(na.Length);
                    if (suffix != "")
                    {
                        suffix = "_" + suffix;
                    }
                    sImageName       = na + suffix + format;
                    sImageName       = sImageName.Replace(" ", "_");
                    Session["Files"] = sImageName;
                }

                else if ((DropDownList1I.SelectedIndex != 0) && (tbDirectoryImage.Text.Length > 0))
                {
                    string width  = ResizeWidth;
                    string height = ResizeHeight;
                    string suffix = ResizeSuffix;
                    Directory.CreateDirectory(dir + DropDownList1I.SelectedItem.Text + "/" + tbDirectoryImage.Text);
                    string name = file.GetName();
                    if (ResizeImage == true)
                    {
                        string path         = DropDownList1I.SelectedItem.Text + "/" + tbDirectoryImage.Text + "/";
                        string physicalpath = Server.MapPath("~/App_Uploads_Img/" + DropDownList1I.SelectedItem.Text + "/" + tbDirectoryImage.Text + "/");

                        // Save temporary file, we'll use this for our resizing then delete it after
                        file.SaveAs(physicalpath + name, true);

                        // Begin resize function
                        resize(name, path, physicalpath, width, height, suffix);
                    }
                    else
                    {
                        string physicalpath = Server.MapPath("~/App_Uploads_Img/" + DropDownList1I.SelectedItem.Text + "/" + tbDirectoryImage.Text + "/");
                        file.SaveAs(physicalpath + name, true);
                    }
                    Session["cat"] = (DropDownList1I.SelectedItem.Text + "/" + tbDirectoryImage.Text);
                    string sFileName = file.GetName().ToLower();
                    string na        = sFileName.Substring(0, sFileName.LastIndexOf("."));
                    string format    = sFileName.Substring(na.Length);
                    if (suffix != "")
                    {
                        suffix = "_" + suffix;
                    }
                    sImageName       = na + suffix + format;
                    sImageName       = sImageName.Replace(" ", "_");
                    Session["Files"] = sImageName;
                }

                else if ((DropDownList1I.SelectedIndex > 0) && (tbDirectoryImage.Text.Length == 0))
                {
                    string width  = ResizeWidth;
                    string height = ResizeHeight;
                    string suffix = ResizeSuffix;
                    string name   = file.GetName();

                    if (ResizeImage == true)
                    {
                        string path         = DropDownList1I.SelectedItem.Text + "/";
                        string physicalpath = Server.MapPath("~/App_Uploads_Img/" + DropDownList1I.SelectedItem.Text + "/");

                        // Save temporary file, we'll use this for our resizing then delete it after
                        file.SaveAs(physicalpath + name, true);

                        // Begin resize function
                        resize(name, path, physicalpath, width, height, suffix);
                    }
                    else
                    {
                        string physicalpath = Server.MapPath("~/App_Uploads_Img/" + DropDownList1I.SelectedItem.Text + "/");
                        file.SaveAs(physicalpath + name, true);
                    }
                    // Assign a session variable so we can auto-select it from the dropdown
                    Session["cat"] = DropDownList1I.SelectedItem.Text;
                    string sFileName = name.ToLower();
                    string na        = sFileName.Substring(0, sFileName.LastIndexOf("."));
                    string format    = sFileName.Substring(na.Length);
                    if (suffix != "")
                    {
                        suffix = "_" + suffix;
                    }
                    sImageName       = na + suffix + format;
                    sImageName       = sImageName.Replace(" ", "_");
                    Session["Files"] = sImageName;
                }
            }
            GC.Collect();
        }

        getfolders(ref al, Server.MapPath("~/App_Uploads_Img/"));
        getallfolders(ref al2, Server.MapPath("~/App_Uploads_Img/"));
        if ((Session["cat"] != null) && (Session["Files"] != null))
        {
            ddCatImage.SelectedValue = Session["cat"].ToString().Replace("\\", "/");
            getfiles(Server.MapPath("~/App_Uploads_Img/") + ddCatImage.SelectedItem.Value);
            string myfiles = Session["Files"].ToString();
            try
            {
                ddFilesImage.SelectedValue = myfiles.ToLower();
            }
            catch (Exception ex)
            { }
            showimage(ddCatImage.SelectedValue, ddFilesImage.SelectedValue);
        }
        tbDirectoryImage.Text = "";
        //UpdatePanel1Image.Update();
        //UpdatePanel2Image.Update();
    }
Exemplo n.º 57
0
        //[ValidateAntiForgeryToken]
        public ActionResult SelectColumns([Bind(Include = "AccountID")] int AccountID,
                                          [Bind(Include = "DateColumn")] int DateColumn,
                                          [Bind(Include = "AmountColumn")] int AmountColumn,
                                          [Bind(Include = "DescriptionColumn")] int DescriptionColumn)
        {
            //Create a new batch and save it to the db.
            Batch batch = new Batch(DateTime.Now);

            db.Batches.Add(batch);
            db.SaveChanges();

            //Variables that track how many rows have succeeded and failed
            int SuccessCount = 0;
            int FailCount    = 0;

            //Create a new parser to parse through the csv file
            string FilePath = Path.Combine(Server.MapPath("~/Content/csv/import.csv"));
            var    parser   = new TextFieldParser(FilePath);

            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(new string[] { "," });

            //This array will contain all the transactions that failed to save to the db and their associated row information
            List <FailedRow> FailedRows = new List <FailedRow>();

            //parse through each row, grab the information from appropiate columns, create a new transaction, and add it to the db
            //if the row is invalid, add it to the failed rows list
            while (!parser.EndOfData)
            {
                //Parse through the next row in the file
                string[] row = parser.ReadFields();

                //These are the variables we will need to create a new transaction
                DateTime date        = new DateTime();
                decimal  amount      = new decimal();
                string   description = "";

                //Error variables.
                bool      ValidRow  = true;
                FailedRow FailedRow = new FailedRow();

                //Determine if the date field can be converted to a date
                try
                {
                    date           = Convert.ToDateTime(row[DateColumn]);
                    FailedRow.Date = date;
                }
                catch
                {
                    FailedRow.invalidDate   = row[DateColumn];
                    FailedRow.ErrorID       = 1;
                    FailedRow.ErrorMessage += "Invalid Date.  Please enter a valid date.\n";
                    ValidRow = false;
                }

                //Determine if the amount field can be converted to a decimal
                try
                {
                    amount           = Decimal.Parse(row[AmountColumn]);
                    FailedRow.Amount = amount;
                }
                catch
                {
                    FailedRow.invalidDate   = row[AmountColumn];
                    FailedRow.ErrorID       = 2;
                    FailedRow.ErrorMessage += "Invalid Amount.  Please enter a valid amount.\n";
                    ValidRow = false;
                }

                //Determine if the description field has a value
                if (row[DescriptionColumn] != "")
                {
                    description           = row[DescriptionColumn];
                    FailedRow.Description = description;
                }
                else
                {
                    FailedRow.ErrorID       = 3;
                    FailedRow.ErrorMessage += "No Description.  Please enter a description.\n";
                    ValidRow = false;
                }

                //Create a transaction from the row and add it to the db if all the fields are valid
                if (ValidRow)
                {
                    Transaction transaction = new Transaction(batch.BatchID, AccountID, date, description, amount, 0);

                    try
                    {
                        //Try to add the transaction to the db.
                        db.Transactions.Add(transaction);
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        //If there is an exception, add an error message and mark the row as invalid
                        db.Transactions.Remove(transaction);
                        FailedRow.ErrorID       = 4;
                        FailedRow.ErrorMessage += "Duplicate transaction cannot be uploaded.\n";
                        ValidRow = false;
                    }
                }

                if (!ValidRow)
                {
                    //If the row is invalid add it to the invalid rows dictionary along with the error message
                    string[] failedrow = { row[DateColumn], row[DescriptionColumn], row[AmountColumn] };
                    FailedRows.Add(FailedRow);
                    FailCount++;
                }
                else
                {
                    SuccessCount++;
                }
            }

            //Add the number of successful and failed rows to the batch
            Batch updateBatch = db.Batches.Find(batch.BatchID);

            updateBatch.SuccessRows     = SuccessCount;
            updateBatch.FailedRows      = FailCount;
            db.Entry(updateBatch).State = EntityState.Modified;
            db.SaveChanges();

            if (FailedRows.Count > 0)
            {
                //If there are failed rows, redirect to ResolveErrors action
                TempData["failedrows"] = FailedRows;
                return(RedirectToAction("ResolveErrors", new { batchid = batch.BatchID }));
            }
            else
            {
                //If there are no failed rows, redirect to Confirmed action
                return(RedirectToAction("FindVendor", "Transaction", new { batchid = batch.BatchID }));
            }

            //Delete the import.csv file
            //FileInfo file = new FileInfo(FilePath);
            //file.Delete();
        }
    private TaskResult Start(IRemoteTaskServer server, TaskExecutionNode node, CSUnitTestFixtureTask fixture)
    {
      server.TaskProgress(fixture, "Instantiating...");
      Type type = GetFixtureType(fixture, server);
      if (type == null)
        return TaskResult.Error;

      string ignoreReason;
      if (IsIgnored(type, out ignoreReason))
      {
        // fixture is ignored
        if (!fixture.Explicitly)
        {
          // check that we don't have any explicitly run test
          bool hasExplicitTest = false;
          foreach (TaskExecutionNode testNode in node.Children)
          {
            if (((CSUnitTestTask) testNode.RemoteTask).Explicitly)
            {
              hasExplicitTest = true;
              break;
            }
          }
          if (!hasExplicitTest)
          {
            server.TaskProgress(fixture, ""); 
            server.TaskFinished(fixture, ignoreReason, TaskResult.Skipped);
            return TaskResult.Skipped;
          }
        }
      }

      ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
      if (ci == null)
      {
        server.TaskError(fixture, string.Format("Cannot find parameterless constructor on type '{0}'", type));
        return TaskResult.Error;
      }

      if (!BuildTypeInfo(server, fixture, type))
        return TaskResult.Error;

      object instance = ci.Invoke(new object[0]);
      if (instance == null)
      {
        server.TaskError(fixture, string.Format("Cannot create instance of type '{0}'", type));
        return TaskResult.Error;
      }

      fixture.Instance = instance;
      if (myFixtureSetUp != null)
      {
        server.TaskProgress(fixture, "Setting up...");
        try
        {
          TaskExecutor.Invoke(fixture.Instance, myFixtureSetUp);
        }
        catch (TargetInvocationException e)
        {
          Exception exception = e.InnerException ?? e;

          string message;
          Server.TaskException(fixture, TaskExecutor.ConvertExceptions(exception, out message));
          Server.TaskFinished(fixture, message, TaskResult.Exception);
          return TaskResult.Exception;
        }
      }

      server.TaskProgress(fixture, "");
      return TaskResult.Success;
    }
Exemplo n.º 59
0
        public ActionResult DesignationMasterPdf()
        {
            string FileName = Path.Combine(Server.MapPath("~/Downloads/DesignationDetails/"));
            string filetodownload = "Designation Report " + DateTime.Now.Date.ToString("dd-MM-yyyy") + ".pdf";


            string pathString = System.IO.Path.Combine(FileName, filetodownload);
            var file = System.IO.File.Create(pathString);
            file.Close();
            FileStream stream = new FileStream(pathString, FileMode.OpenOrCreate);
            Document doc = new Document(PageSize.A4.Rotate(), 40f, 40f, 20f, 20f);
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, stream);

            var F = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, BaseColor.WHITE);
            var H = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10, BaseColor.WHITE);
            var P = new BaseColor(102, 51, 153);
            var I = FontFactory.GetFont(FontFactory.HELVETICA, 9, P);


            DataTable dt = new DataTable();
            SqlConnection SqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["MSSQL_ConnectionString"].ConnectionString);
            SqlCommand Sqlcomrep = new SqlCommand();
            Sqlcomrep.Connection = SqlCon;
            Sqlcomrep.CommandType = CommandType.StoredProcedure;
            Sqlcomrep.CommandTimeout = 500;
            Sqlcomrep.CommandText = "DesignationMList_get";

            SqlDataAdapter sqlda = new SqlDataAdapter(Sqlcomrep);
            SqlCon.Open();
            sqlda.Fill(dt);
            SqlCon.Close();



            //////////////////////////////////////////////////////////
            PdfPTable table0 = new PdfPTable(1);
            //table0.DefaultCell.Border = Rectangle.NO_BORDER;
            table0.WidthPercentage = 40;
            table0.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell cell0;
            cell0 = new PdfPCell(new Phrase("DESIGNATION MASTER", F));
            cell0.VerticalAlignment = Element.ALIGN_MIDDLE;
            cell0.HorizontalAlignment = Element.ALIGN_CENTER;
            cell0.PaddingTop = 5;
            cell0.PaddingBottom = 7;
            // cell0.Rowspan = 3;
            cell0.BackgroundColor = new BaseColor(0, 119, 142);
            table0.AddCell(cell0);

            ////////////////////////////////////////////////////////////

            PdfPTable table = new PdfPTable(5);
            table.WidthPercentage = 40;

            PdfPCell cell;
            cell = new PdfPCell(new Phrase("Sl.No", H));
            cell.Colspan = 1;
            cell.PaddingBottom = 5;
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BackgroundColor = new BaseColor(0, 119, 142);
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase("DESIGNATION NAME", H));
            cell.PaddingBottom = 5;
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.Colspan = 4;
            cell.BackgroundColor = new BaseColor(0, 119, 142);
            table.AddCell(cell);




            ///////////////////////////////

            int slno = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                slno = slno + 1;
                cell = new PdfPCell(new Phrase(slno.ToString(), I));
                cell.Colspan = 1;
                cell.PaddingBottom = 5;
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                table.AddCell(cell);

                // cell = new PdfPCell(new Phrase("aaaaaaaaaaaaaa", I));
                cell = new PdfPCell(new Phrase(dt.Rows[i].Field<string>("DesignationName").ToString(), I));
                cell.Colspan = 4;
                cell.PaddingBottom = 5;
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                table.AddCell(cell);


            }

            // table0.SpacingBefore = 10f;
            table0.SpacingAfter = 12.5f;
            //  table.SpacingBefore = 10f;
            // table.SpacingAfter = 12.5f;

            doc.Open();
            doc.Add(table0);
            doc.Add(table);
            doc.Close();

            return Json(filetodownload);
        }
Exemplo n.º 60
0
        // GET: Upload/SelectColumns

        /* This action parses through the first row of the CSV file and generates
         * a list of columns containing the column number and an example of the column
         * value so the user can associate what columns are associated with the different
         * transaction information
         */
        public ActionResult SelectColumns(int accountid)
        {
            //Pass the account id to the viewbag
            ViewBag.AccountID = accountid;

            //Create a new parser to parse through the csv file
            string FilePath = Path.Combine(Server.MapPath("~/Content/csv/import.csv"));
            var    parser   = new TextFieldParser(FilePath);

            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(new string[] { "," });

            //Create a list of date columns, amount columns, and text columns
            ViewBag.datecolumns   = new List <Column>();
            ViewBag.amountcolumns = new List <Column>();
            ViewBag.textcolumns   = new List <Column>();

            //Parse the first row of the file to get an example of each piece of data.
            string[] firstrow = parser.ReadFields();

            /* Check each record in the first row.
             * If it is empty, throw it out
             * If it contains a value that can be parsed to a date, add it to the date columns
             * If it contains a value that can be parsed to an integer, add it to the amount column
             * If it just contains text, add it to the text column
             */
            for (int i = 0; i < firstrow.Length; i++)
            {
                //Create the column (column number, column value)
                Column column = new Column(i, firstrow[i]);

                try
                {
                    //try converting to a date
                    Convert.ToDateTime(firstrow[i]);
                    ViewBag.datecolumns.Add(column);
                }
                catch
                {
                    try
                    {
                        //try converting to a decimal
                        Decimal.Parse(firstrow[i]);
                        ViewBag.amountcolumns.Add(column);
                    }
                    catch
                    {
                        if (firstrow[i] != "")
                        {
                            //If not empty, add to textcolumns
                            ViewBag.textcolumns.Add(column);
                        }
                    }
                }
            }

            /* Pass the list of columns to the view where the user can select
             * which columns are associated with the transaction amount, date
             * and description.
             */
            return(View());
        }