Posts

Showing posts with the label Code Snippet

C#: Converting a Datatable to XML

Given a .Net datatable filled with data and an explicitly defined name and columns, we can extract it's XML in the following manner.  public static XmlDocument ConvertToXML(DataTable dt)         {                     string sXML;            using (StringWriter sw = new StringWriter())            {                dt.WriteXml(sw);                sXML = sw.ToString();            }            //Althought the following code is also working fine            //MemoryStream mstr = new MemoryStream();            //dt.WriteXml(mstr, true);            //mstr.Seek(0, SeekOrigin.Begin);           ...

Getting JSON output from ASP.Net WebMethod

Althought ASP.Net Webservice provides a very convenient way to develop a Webservice but it just returns XML. At time we need this webservice to return JSON. Here is a tiny trick that makes an XML based webmethod to rueturn JSON. [ScriptMethod(ResponseFormat = ResponseFormat.Json)] [WebMethod(Description = "To gets a list of available customers")]     public string GetCustomerList(string strToken)     {         try         {             SPCustomers objCust = new SPCustomers();                       ArrayList arlstCusomers = new ArrayList();             arlstCusomers = objCust.GetList();             JavaScriptSerializer js = new JavaScriptSerializer(arlstCusomers);             string strJson = js.Serialize();         ...

Uploading Files to FTP Site using .Net

Using System.Net lets us access, Download, Upload ,Delete, See All files, and variety of other primitive tasks over FTP site. Here is the C# code that lets us upload the files to a specific FTP URL. private void Upload(string filename) { FileInfo fileInf = new FileInfo(filename); string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name; FtpWebRequest reqFTP; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));   // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);   // By default KeepAlive is true, where the control connection is //not closed after a command is executed. reqFTP.KeepAlive = false;   // Specify the command to be executed. // Specify the data transfer type.  reqFTP.Method = WebR...

Converting Currency in Digits to Currency in Words

The other day, I came across another issue related to Software Dev that demanded conversion of currency in digit to Currency in words. Since it was an urgent CR so I took a code from the site below.   http://www.eggheadcafe.com/community/aspnet/2/10018714/convert-number--into-word.aspx But few days latter the QA figured out a bug where my application read 1024 as One thousand and Hundred and Twenty Four and I knew I was in a deep trouble this time, since the code wasn't mine and I was answerable. So I had to understand the code and make some +ve amendments and I am happy that I havent lost the flair for programming that I had during my graduation. So below is the code courtesy of the site above. #region Code For Currency Conversion public String changeNumericToWords(double numb) { String num = numb.ToString(); return changeToWords(num, false); } public String changeCurrencyToWords(String numb) { ...

Dynamically assigning The Configuration file path

Though it can be a real securuity hazard to keep the Configuation file out of the scopem where the application resides since it may cause unavailability of file sometimes. But somehow we need to do that and here is the way we can do this in the Windows Apps. 1. just paste following line in the Program.Cs file before Application.Run(new Form1()); AppDomain.CurrentDomain.SetData("AppConfig", "D:\\Test.config"); 2. Now the data in the appsettings and you'll find the data you require for instance string confData = ConfigurationManager.AppSettings["FilePath"]; 4. The above way will permanantly change the path of the config File. If the requirement is to just address another file and then switching batch to the orginal one, then here is the code Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFilePath, ConfigurationUserLevel.None); AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings"); stri...

Stored Procedures Tips and tricks

Here I am posting a Stored procedure created using few of the effective techniques that I have been using frequently over the past few days. Here are the ingredients of the SP given below, At certain point in time we ought to test the application for sanity over the Production machine and don't want the data to be visible later on but for very obvious reasons we can't remove that data since there are a lot of dependencies (Foreign References ) over it. We can hide it using the techniques demonstrated in the SP below in Red Color. Using the "Cases" in the SQL that can let one output understandable statements based on the given Auto or ID. It also demonstrated the fact that we try to do most of the data processing work in the SPs rather than totally relying on the code. Generally, most of us use the SP to get our datasets filled with the raw unformatted and unprocessed data whose kinks are ironed out in the code in the later stages. Trivial issues like date format...

Converting a string to Query in SQL Server

declare @a varchar(20) declare @qry nvarchar(200) set @a = '235,236,237' set @qry = N'select * from students where stdID in (' + @a + ')' exec sp_executesql @qry

Reading Data From Excel File

Excel2007 works on the XML and there are several ways to retrive data from the Excel2007 file but below is the common method. Just changing the connection string ,lets us read other previous versions too. private DataSet openXLSFile(string filePath) { String sConnectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0"; OleDbConnection objConn = new OleDbConnection(sConnectionString); objConn.Open(); objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn); objAdapter = new OleDbDataAdapter(); objAdapter.SelectCommand = objCmdSelect; objDataset = new DataSet(); objAdapter.Fill(objDataset, "CSVData"); objConn.Close(); return objDataset; }