How to Delete Files Directory Sub Directories in Asp.Net

Description:-

Files Directory is nothing but in computing, a directory is a file system cataloging structure which contains references to other computer files, and possibly other directories. A file can be fully and uniquely identified by its full name, including all directories to which it belongs. In this Example we will Delete File from File using File Directory in dotnet.

In your Webpage Drag Gridview controls so we can see all file easily. Files name, size, directory info and location actually where are the file. And in Column Create Link controls for Deleting file.

<div>
   <asp:GridView ID="gridviewDeleteFiles" runat="server" OnRowCommand="gridviewDeleteFiles_RowCommand" OnRowDeleting="gridviewDeleteFiles_RowDeleting">
      <Columns>
         <asp:ButtonField Text="Delete" CommandName="Delete" />
      </Columns>
   </asp:GridView>
</div>

Now go to Code behind and get all File Directory from Specified URL Code in Page Load so When First time page Call then get all files from that URL. Here I have Created Method and call in page load event.

Protected void Page_Load(object sender, EventArgs e)
{
  FillGridView();
}

Private void FillGridView()
{
  DataTable dtGridViewSource = new DataTable();
  dtGridViewSource.Columns.Add(new DataColumn("Name", typeof(System.String)));
  dtGridViewSource.Columns.Add(new DataColumn("Size", typeof(System.String)));
  dtGridViewSource.Columns.Add(new DataColumn("Type", typeof(System.String)));
  dtGridViewSource.Columns.Add(new DataColumn("Path", typeof(System.String)));
  DataRow gridviewRow;
  //Get All Folders Or Directories and add in table
  DirectoryInfo directory = new  DirectoryInfo(Server.MapPath("~/C:/Users/Umesh/Desktop"));
  DirectoryInfo[] subDirectories = directory.GetDirectories();
  foreach (DirectoryInfo dirInfo in subDirectories)
  {
    gridviewRow = dtGridViewSource.NewRow();
    gridviewRow["Name"] = dirInfo.Name;
    gridviewRow["Type"] = "Directory";
    gridviewRow["Path"] = dirInfo.FullName;
    dtGridViewSource.Rows.Add(gridviewRow);
  }
  //Get files in all directories 
  FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);
  foreach (FileInfo fileInfo in files)
  {
   gridviewRow = dtGridViewSource.NewRow();
   gridviewRow["Name"] = fileInfo.Name;
   gridviewRow["Size"] = fileInfo.Length;
   gridviewRow["Type"] = "File";
   gridviewRow["Path"] = fileInfo.FullName;
   dtGridViewSource.Rows.Add(gridviewRow);
  }
  gridviewDeleteFiles.DataSource = dtGridViewSource;
  gridviewDeleteFiles.DataBind();
}

In DirectoryInfo I have given my Desktop location so there I can delete file. Now generate Gridview Row Command event SO from Gridview we can delete that Particular from location.

Protected void gridviewDeleteFiles_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Delete")
  {
      GridViewRow row = gridviewDeleteFiles.Rows[Convert.ToInt32(e.CommandArgument)];
      string fileName = row.Cells[1].Text;
      string filePath = row.Cells[4].Text;
      string type = row.Cells[3].Text;
      if (type == "File")
      {
         System.IO.File.Delete(filePath);
      }
      else if (type == "Directory")
      {
         System.IO.Directory.Delete(filePath, true);
      }
  }
  FillGridView();
}

Now run your Webpage and there you can see files from Specified location. Now delete one file and that file also delete from original location.

How to Create Ajax Modal Popup Extender in Asp.Net


Description:-

In this Article we will Explain how to Crate Ajax Model Popup Extender in Webpage without Postback page. We will Use Button Control to Show Model Popup and Without Postback we will Use Model Popup in Webpage when we close it then we have to Postback our page so let’s start how to Achieve this functionality in dot net.

Default.aspx:-

<cc1:toolkitscriptmanager runat="server">
</cc1:toolkitscriptmanager>
<asp:Button ID="btnShow" runat="server" Text="Show Modal Popup" />
<!-- ModalPopupExtender -->
<cc1:modalpopupextender id="mp1" runat="server" popupcontrolid="Panel1" targetcontrolid="btnShow"
   cancelcontrolid="btnClose" backgroundcssclass="modalBackground">
</cc1:modalpopupextender>
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" align="center" Style="display: none">
   <div style="height: 100px">
      Do you like this product?&nbsp;
      <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="OnSelectedIndexChanged">
         <asp:ListItem Text="Please Select" Value="0"></asp:ListItem>
         <asp:ListItem Text="Yes" Value="1"></asp:ListItem>
         <asp:ListItem Text="No" Value="2"></asp:ListItem>
      </asp:DropDownList>
   </div>
   <asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>

Here we have set OnSelectedIndexChanged Property of DropDownList and Bind ModelPopup Exteder by Close in Model Popup.

Register AjaxControlToolKit in your Webpage.

<%@RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"Tagprefix="cc1"%>

Style:-

<style type="text/css">
   body
   {
   font-family: Arial;
   font-size: 10pt;
   }
   .modalBackground
   {
   background-color: Black;
   filter: alpha(opacity=90);
   opacity: 0.8;
   }
   .modalPopup
   {
   background-color: #fff;
   border: 3px solid #ccc;
   padding: 10px;
   width: 300px;
   }
</style>

On Code behind File we have to Change DropDownList Control Event and bind Popup Extender Controls.

protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
   mp1.Show();
}

Now Run your Application and Click on Button to Show Popup a Changed your Selection from DropDownList and Click on Close.
Auto generate gridview row in asp.net

Auto generate gridview row in asp.net

Description:-

In this article we will see about Auto GenerateGridview Row in Dot net. Here I have created sample demo example to understand easily in dot net. Here I have bind Gridview data from database and display in webpage. For example I have used country table to get data from that table and display on webpage.

I have used Container to get Gridview row Index and add dynamically in Gridview to Increment based on Item Index. To use we have to add it on Itemtemplate in Gridview.

<%# Container.DataItemIndex + 1 %>

Now Bind Gridview data from Database and Display it on Webpage.

Create Table:-
Create Table and Name it "Country".

CREATE TABLE [dbo].[Country](
 [CountryID] [bigint] IDENTITY(1,1) NOT NULL,
 [CountryName] [varchar](50) NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED 
(
 [CountryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Default.aspx:-

<div>
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="#BFE4FF" />
      <Columns>
        <asp:TemplateField HeaderText="Sr.No.">
          <ItemTemplate>
            <%# Container.DataItemIndex + 1 %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="CountryName" HeaderText="CountryName" />
      </Columns>
  </asp:GridView>
</div>

Default.aspx.cs:-

protected void Page_Load(object sender, EventArgs e)
{
  SqlDataAdapter adapter = new SqlDataAdapter();
  DataSet ds = new DataSet();
  int i = 0;
  string sql = null;
  string connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True";
  sql = "select * from Country";
  SqlConnection connection = new SqlConnection(connetionString);
  connection.Open();
  SqlCommand command = new SqlCommand(sql, connection);
  adapter.SelectCommand = command;
  adapter.Fill(ds);
  adapter.Dispose();
  command.Dispose();
  connection.Close();
  GridView1.DataSource = ds.Tables[0];
  GridView1.DataBind();
}

How to Generate QRCode in Asp.Net


Description:-

In this article we will generate QRCode from Input Textbox value and store in QRCode. Here we will use Textbox Control and Button Control to Generate QRCode and use QRCode Reference to generate it.

Download file:- QRCoder.dll

Default.aspx:-
Drag Textbox and Button and Placeholder Control in your Webpage.

<div>
   <asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
   <asp:ButtonID="btnGenerate"runat="server"Text="Generate"OnClick="btnGenerate_Click" />
   <hr />
   <asp:PlaceHolder ID="plBarCode" runat="server" />
</div>

Default.aspx.cs:-
Now Go to Code behind File and Code for Generate QRCode on button click event.

protected void btnGenerate_Click(object sender, EventArgs e)
{
    string code = txtCode.Text;
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
    System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
    imgBarCode.Height = 150;
    imgBarCode.Width = 150;
    using (Bitmap bitMap = qrCode.GetGraphic(20))
    {
        using (MemoryStream ms = new MemoryStream())
        {
            bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] byteImage = ms.ToArray();
            imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
        }
        plBarCode.Controls.Add(imgBarCode);
    }
}


Here we will generate image based on inputted value and display in Placeholder.
Now run your Webpage and input value in textbox to generate QRCode.

IP LookUp Program in Asp.Net

IP LookUp Program in Asp.Net

Description:- 

IP look up program that uses C# Windows Forms and IPHostEntry to resolve the DNS request. You enter the URL in the first box and press the Look Up button and the IP shows in the bottom box.

I created the controls, instead of using the form designer and in doing so the placement is not that great. But it should give a very basic example of creating your own controls and how the IPHostEntry works.

Name Spaces:-


using System;
using System.IO;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Text;

Code:-

        TextBox txtBox1;
        TextBox txtBox2;
        string address;
        string IPaddress;
        public IPLookUp()
        {
            Text = "IP Look Up";
            BackColor = Color.White;
            txtBox1 = new TextBox();
            txtBox1.Parent = this;
            txtBox1.Text = "Enter URL";
            txtBox1.Location = new Point(Font.Height * 6, Font.Height * 2);
            Button btnlook = new Button();
            btnlook.Parent = this;
            btnlook.BackColor = SystemColors.ControlDark;
            btnlook.Text = "Look UP";
            btnlook.Location = new Point(Font.Height * 7, Font.Height * 6);
            btnlook.Click += new EventHandler(button1_Click);
            Label label = new Label();
            label.Parent = this;
            label.Text = "IP Address";
            label.Location = new Point(Font.Height * 6, Font.Height * 10);
            txtBox2 = new TextBox();
            txtBox2.Parent = this;
            txtBox2.Text = " ";
            txtBox2.Location = new Point(Font.Height * 6, Font.Height * 12);
            Button btnquit = new Button();
            btnquit.Parent = this;
            btnquit.BackColor = SystemColors.ControlDark;
            btnquit.Text = "Quit";
            btnquit.Location = new Point(Font.Height * 7, Font.Height * 16);
            btnquit.Click += new EventHandler(button2_Click);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            address = txtBox1.Text;
            GetIP(address);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void GetIP(string address)
        {
            try
            {
                IPHostEntry IPHost = Dns.Resolve(address);
                IPAddress[] addresses = IPHost.AddressList;
                IPaddress = addresses[0].ToString();
                txtBox2.Text = IPaddress;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        public static void Main()
        {
            Application.Run(new IPLookUp());
        }
How to get EximPort and ProductGroup from AdvanceLicense in ax 2012

How to get EximPort and ProductGroup from AdvanceLicense in ax 2012

Description: - 

In this article we will see about how to get Exim Port and Product Group from Advance License Number.

Here I have given simple demonstration to get Exim Port and Product Group from advance license number in sales order or in purchase order.

If you have advance license number and based on that number you have to get Exim Port and Product Group for that advance license number then you can get by below code.

In you sales order just create modified method in advance license field and paste below code to get Exim Port and Product Group.

Code:- 

EximSalesLine_IN.EximPorts = EximIncentiveSchemeGroup_IN::find(EximSalesLine_IN.EximIncentiveSchemeGroup).EximPortId;
 
EximSalesLine_IN.EximProductGroupTable = EximIncentiveSchemeData_IN::findSchemeId(EximSalesLine_IN.EximIncentiveSchemeGroup).EximProductGroupTable; 

Custom FormDatasource lookup in Ax

Description:- 
The following sample demonstrates how to add custom lookup to DataSource field on an AX form

public void lookup(FormControl _formControl, str _filterStr)
{
    SysTableLookup sysTableLookup; // systemclass to create //customlookup
    Query query;
    QueryBuildDataSource qbd;
    ;
    sysTableLookup = SysTableLookup::newParameters(tablenum(A_PurchaseOrder),_formcontrol);
    //Construct query on the table,
    //whose records you want to show as lookup.
    query = new Query();
    qbd = query.addDataSource(tablenum(A_PurchaseOrder));
    qbd.addRange(fieldnum(A_PurchaseOrder,Status)).value(SysQuery::value(enum2str(PO_Status::Close)));
    // add the fields to the lookup list
    sysTableLookup.addLookupfield(fieldnum(A_PurchaseOrder,Purchase_ID));
    sysTableLookup.addLookupfield(fieldnum(A_PurchaseOrder,Vender_Code));
    // pass the query as parameter
    // system will show the records in the lookup
    // as per your query
    sysTableLookup.parmQuery(query);
    sysTableLookup.performFormLookup();
}
How to update query in list page per user in ax 2012

How to update query in list page per user in ax 2012

Description:-

In this article we will see about how to changes to update query range in listpage in Ax 2012.
Here I have given simple demonstration to update or modify query in list page per user in Ax 2012.
For Example: here I have took purchase listpage and in that listpage I have to update datquery for particular user so he/she can see only that data. For that I have changed in PurchTableListPageInteraction Class initializeQuery Method add user range for particular user, so that user can see that data what I have passed in range.

In Purchtable I have set on that user can see Confirmed and Approved which DocumentState have.
And which PurchStatus have OpenOrder and Received.
Or else you can see here how to pass multiple Enum range in query.
Like below.

if(curUserId() == "Username")
{
    qbds = _query.dataSourceTable(tableNum(PurchTable));
    qbds.addRange(fieldNum(PurchTable,DocumentState)).value(strfmt("%1,%2",enum2str(VersioningDocumentState::Approved),enum2str(VersioningDocumentState::Confirmed)));

    qbds.addRange(fieldNum(PurchTable,PurchStatus)).value(strfmt("%1,%2",enum2str(PurchStatus::Backorder),enum2str(PurchStatus::Received)));
} 
get Invoice and delivired Customer Address in dynamics ax

get Invoice and delivired Customer Address in dynamics ax

Description:-

In this article we will see about how to get invoice and delivered customer list and write into text file. To get list of all customer and save into text file here is the code to get the customer list with check if Invoice and delivery address is there or not. To save into text file we create text file into destination and run the job in Ax.

Code:-

static void GetInvoice_DeliveryCustomerAddress(Args _args)
{
    Addressing address,address1;
    DirPartyRecId party;
    CustTable CustTable;
    BinData binData,binData1;
    TextBuffer textBuffer,textBuffer1;
    
    textBuffer = new TextBuffer();
    textBuffer.setText('');    
    textBuffer1 = new TextBuffer();
    textBuffer1.setText('');
    
    while select CustTable
    {
      party = CustTable::find(CustTable.AccountNum).Party;
      //Invoice
      address = DirParty::getPostalAddressByType(party,LogisticsLocationRoleType::Invoice);
      //Delivery
      address1 = DirParty::getPostalAddressByType(party,LogisticsLocationRoleType::Delivery);
      //If get Invoice and delivery Checked
      if (address && address1)
      {
          textBuffer.appendText(strfmt('%1\r\n',CustTable.AccountNum));
      }
      //If get Invoice and delivery NotChecked
      else if(!address && !address1)
      {
          textBuffer1.appendText(strfmt('%1\r\n',CustTable.AccountNum));
      }
        
      textBuffer.getText();
      binData = new BinData();
      binData.setStrData(textBuffer.getText());
      binData.saveFile(@"Text File Location");
        
      textBuffer1.getText();
      binData1 = new BinData();
      binData1.setStrData(textBuffer1.getText());
      binData1.saveFile(@"Text File Location");
    }
}

Note:- Here I have get customer address like invoice and delivery. if you want selected only one then you can put || (OR) condition. One customer have selected for invoice and another customer has delivery checked and in Code if you have put || (OR) condition then you can get both customer.
How to Check Current Session Id in Ax

How to Check Current Session Id in Ax

Description:-

You can retrieve the current client session id by using the following function: SessionId().

So, for example in a job, to show the current session id

static void ClientSessionJob(Args _args)
{
    ;
    info(strfmt('Client Session id-%1',int2str(SessionId())));
}

You can use this function together with the class xSession to collect more info.
The class xSession is responsible for retrieving various session information. Like the logon date and time:

static void LogonDateTime(Args _args)
{
    xSessionxSession;
    ;
    xSession = new xSession(SessionId());
    info(strfmt('logon date and time - %1',DateTimeUtil::toStr(xSession.loginDateTime())));
}

Or the current AOS server name you're logged onto:

static void CurAOSServerName(Args _args)
{
    xSessionxSession;
    ;
    xSession = new xSession();
    info(strfmt('Current AOS server name-%1',xSession.AOSName()));
}

Instantiate the class xSession without a session id to get info for the current session.
The user id used to create the session is also available. But there is an alternative for this one:

static void ClientUserId(Args _args)
{
    ;
    info(strfmt('Current user id-%1',curUserId()));
}