Monday, May 2, 2016

Reading data from a xml string

string xmlString =  "Names" +
                        "Name" +
                            "FirstName John /FirstName" +
                            "LastName Smith /LastName" +
                        "/Name" +
                        "Name" +
                            "FirstName James /FirstName" +
                            "LastName White /LastName" +
                        "/Name" +
                    "/Names";

XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlString);

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
    string firstName = xn["FirstName"].InnerText;
    string lastName = xn["LastName"].InnerText;
    Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

Thursday, October 15, 2015

Logging into database using Enterprise Logging


Database _database = DatabaseFactory.CreateDatabase();
DbCommand _command = _database.GetStoredProcCommand("STOREDPROCEDURENAME");
_database.AddInParameter(_command, "@FIELDNAME", DbType.String, "FIELDVALUE");
_database.ExecuteNonQuery(_command);

Wednesday, July 22, 2015

Get the query string value from URL using javascript

 function getQueryString(key){
         var regex=new RegExp('[\\?&]'+key+'=([^&#]*)');
         var qs=regex.exec(window.location.href);
         return qs[1];
       }

Friday, February 20, 2015

Print a selected area on a page

On the style tag add the below contents

style type="text/css" media="print"
.no-print { display: none; }

The contents which do not have to be printed can be given under a div tag with the class name "no=print"


Friday, February 13, 2015

Upload multiple files using jQuery plugin


  • Refer the jquery.MultiFile.js
  • Add a ASP.Net file upload control to the page
  • Add the following code on the button click event for uploading the files

HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
    HttpPostedFile uploadfile = fileCollection[i];
    string fileName = Path.GetFileName(uploadfile.FileName);
    if (uploadfile.ContentLength > 0)
    {
        uploadfile.SaveAs(Server.MapPath("~/UploadedFiles/") + fileName);
        lblMessage.Text += fileName + "Saved!!!";
    }
}

The multiple file upload plugin can be downloaded from here

Friday, January 23, 2015

Monday, December 29, 2014

Consuming a REST service

            string jsonRequest = "REST URL";
            CredentialCache credCache = new CredentialCache();
            credCache.Add(new Uri(jsonRequest), "NTLM", CredentialCache.DefaultNetworkCredentials);
            HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(jsonRequest);
            spRequest.Credentials = credCache;
            spRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
            spRequest.Method = "GET";
            spRequest.Accept = "application/json;odata=verbose";
            HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();

            if (endpointResponse.StatusCode == HttpStatusCode.OK)
            {
                using (endpointResponse)
                {
                    using (var reader = new StreamReader(endpointResponse.GetResponseStream()))
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        try
                        {
                            string jSON = reader.ReadToEnd();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
            }

Tuesday, August 5, 2014

Grouping datatable column using LINQ in C#

 Grouping datatable column using LINQ in C#


var grouped = from table in dt.AsEnumerable()
                          group table by new { placeCol = table["Place"] } into groupby
                          select new
                          {
                              Value = groupby.Key,
                              ColumnValues = groupby
                          };

            foreach (var key in grouped)
            {               
                Console.WriteLine(key.Value.placeCol);
                Console.WriteLine("---------------------------");
                foreach (var columnValue in key.ColumnValues)
                {
                    Console.WriteLine(columnValue["Name"].ToString());                   
                }
                Console.WriteLine();
            }
            Console.ReadLine();

For additional info:

Saturday, December 1, 2012

How to add a dll to GAC in Windows 7


How to add a dll to GAC in Windows 7

Today I started developing SharePoint application in Win 7 and faced some peculiar issue - I was not able to drag and drop my applications assembly into the gac. So, here comes the main points that you need to keep in mind to deploy one assembly in Win 7 GAC:

1. You must be a member of the Administrator Group.

2. Navigate to "C:\Windows\assembly" in the explorer and right click on it and select "Open in new window".

3. Type 'cmd' in run and as it appears in the top, right click on it and select "Run as administrator".

4. In the command prompt navigate to "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64"

5. Now use the following command: gacutil -i "full path of the file system\XYZ.dll"

6. You will get a message "Assembly successfully added to the cache"

7. Refresh the assembly folder that you have opened in step 2 and you will find your applications assembly there.

http://www.thespgeek.com/2010/11/how-to-add-dll-to-gac-in-windows-7.html

Wednesday, August 8, 2012

Overflow hidden on table - displaying without scroll bar

<table style="width:50%;table-layout:fixed;">
<tr>
<td style="overflow:hidden;white-space:nowrap;">The Writing Life: The point of the long and winding sentence The Writing Life: The point of the long and winding sentence</td>
</tr>
</table>

Remove all special characeter in String.


Remove all special characeter in String.
string title = "You, should be <careful. with , (your current approach) ";
title = Regex.Replace(title, "[^0-9a-zA-Z]+", " ");

Output:
You should be careful with your current approach

Regex.Replace(title, "[^0-9a-zA-Z]+", ""); -- also Remove Space.

Output:
Youshouldbecarefulwithyourcurrentapproach

Monday, July 30, 2012

IE text-decoration with images issues

<style type="text/css">
img{
border:0px;
}
img a, img a:link, img a:active, img a:visited, img a:hover{
border:0px;
}
</style>

Monday, February 20, 2012

Removing duplicates from a collection

List list = new List();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(3);
list.Add(4);
list.Add(4);
List distinct = list.Distinct().ToList();

Wednesday, January 18, 2012

Using multiple data reader

To use multiple data reader objects add MultipleActiveResultSets="True" with in the connection string.

Monday, November 21, 2011

Running PowerShell script from C#

To run the PowerShell scripts from C# add a reference to System.Management.Automation assembly and include the following namespaces

using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

private string RunScript(string scriptText)
{
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);
    pipeline.Commands.Add("Out-String");
    Collection results = pipeline.Invoke();
    runspace.Close();
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }
    return stringBuilder.ToString();
}

Friday, November 18, 2011

Export GridView in ASP.NET to excel

protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=ExportFile.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
gvReport.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

Error in IIS (‘\\?\C:\Windows\system32\inetsrv\config\applicationHost.config’, line number ’0′. The error message is: ‘Configuration file is not well-formed XML’)

Copy the applicationHost.config file from C:\inetpub\history\ in to C:\Windows\System32\inetsrv\config\

This solves the IIS issue.

Formatting Dates, Times and Numbers in ASP.NET

Click here

Monday, October 31, 2011

Get week number from a given date

public static int GetWeekNumber(string date)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime dt = DateTime.ParseExact(date,"dd-MM-yyyy",null);
System.Globalization.Calendar cal = dfi.Calendar;
return cal.GetWeekOfYear(dt, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
}

Thursday, October 27, 2011

Get the first day of week from the week number

public string GetFirstDayOfWeek(int weekNum)
{
DateTime dt = new DateTime(DateTime.Now.Year, 1, 1);
int days = (weekNum) * 7;
DateTime dt1 = dt.AddDays(days);
DayOfWeek dow = dt1.DayOfWeek;
DateTime startDateOfWeek = dt1.AddDays(-(int)dow);
return startDateOfWeek.ToString("dd MMM");
}
public static string GetFirstDayOfWeek(DateTime dayInWeek)
{
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
DateTime firstDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
firstDayInWeek = firstDayInWeek.AddDays(-1);
return firstDayInWeek;
}