Monday, December 3, 2012

Install named instance of sqlserver using batch file

Be aware of the quotes.
ExecWait '"$TEMP\SQLEXPR.EXE" /Silent /INSTANCENAME=SQLEXPRESS ADDLOCAL=All PIDKEY=ABCDE12345FGHIJ67890KLMNO SAPWD=StrongPassword SQLACCOUNT=SQLEXPRESS\bla SQLPASSWORD=blabla AGTACCOUNT=SQLEXPRESS\bla AGTPASSWORD=blabla SQLBROWSERACCOUNT=sqlexpress\bla SQLBROWSERPASSWORD=blabla'

Need to delete Files having more than 3 Underscores ( _ )

Try this code may help u .


void deleteFiles() 
{
DirectoryInfo objDir = new DirectoryInfo(@"D:\");
FileInfo[] objFileList = objDir.GetFiles();
foreach(FileInfo f in objFileList)
{
if (f != null)

if (f.Name.Split('_').Length > 3)
{
f.Delete();
}
}
});



Wednesday, August 8, 2012

E Books For Shrepoint

Please go through this link to download Large collection of Free Microsoft eBooks, including: SharePoint, Visual Studio, Windows Phone, Windows 8, Office 365, Office 2010, SQL Server 2012, Azure, and more for free


http://blogs.msdn.com/b/mssmallbiz/archive/2012/07/27/10334262.aspx

Monday, June 25, 2012

VB^ Code for File OPerations

Public Function DeleteFile(strPath As String) As String
On Error GoTo Error
If FSO.FileExists(strPath) Then
FSO.DeleteFile (strPath)
End If
Error:
MsgBox ("DeleteFile : " & Err.Description)
End Function
Public Function MoveFile(ByVal strSrcPath As String, ByVal strDestPath As String) As String
On Error GoTo Error
If FSO.FileExists(strSrcPath) Then
FSO.MoveFile strSrcPath, strDestPath

End If
Error:
MsgBox ("MoveFile : " & Err.Description)
End Function
Public Function ReadFile(ByVal strFilePath As String) As String
On Error GoTo Error
Dim strOutput As String
If FSO.FileExists(strFilePath) = False Then
Exit Function
End If
Dim nFileNum As Integer, sText As String, sNextLine As String, lLineCount As Long
nFileNum = FreeFile
Open strFilePath For Input As nFileNum
lLineCount = 1
' Read the contents of the file
Do While Not EOF(nFileNum)
   Line Input #nFileNum, sNextLine
   'do something with it
   'add line numbers to it, in this case!
   sNextLine = sNextLine & vbCrLf
   sText = sText & sNextLine
Loop
strOutput = sText

Error:
MsgBox ("ReadFile : " & Err.Description & strOutput)
End Function
Public Function WriteFile(strFilePath As String, strToWriteFilePath As String) As String
On Error GoTo Error
Dim strOutput As String
If fso.FileExists(strFilePath) = False Then
Exit Function
End If
Dim nFileNum As Integer, sText As String, sNextLine As String, lLineCount As Long
nFileNum = FreeFile
Open strFilePath For Input As nFileNum
lLineCount = 1
' Read the contents of the file
Do While Not EOF(nFileNum)
   Line Input #nFileNum, sNextLine
  
   sNextLine = sNextLine & vbCrLf
   sText = sText & sNextLine
Loop
strOutput = sText
Dim newFIle
Set fso = CreateObject("Scripting.FileSystemObject")
 Set newFIle = fso.CreateTextFile(strToWriteFilePath, True, False)
newFIle.Write strOutput


Error:
MsgBox ("WriteFile : " & Err.Description & strOutput)
End Function

Sunday, June 10, 2012

File Upload using FtpWebRequest in .Net C#

Namespace used:
  1. using System.Net;   
  2. using System.IO;  

Sample Code:
  1. public void ftpfile(string ftpfilepath, string inputfilepath)   
  2. {   
  3.     string ftphost = "127.0.0.1";   
  4.     //here correct hostname or IP of the ftp server to be given   
  5.   
  6.     string ftpfullpath = "ftp://" + ftphost + ftpfilepath;   
  7.     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);   
  8.     ftp.Credentials = new NetworkCredential("userid""password");   
  9.     //userid and password for the ftp server to given   
  10.   
  11.     ftp.KeepAlive = true;   
  12.     ftp.UseBinary = true;   
  13.     ftp.Method = WebRequestMethods.Ftp.UploadFile;   
  14.     FileStream fs = File.OpenRead(inputfilepath);   
  15.     byte[] buffer = new byte[fs.Length];   
  16.     fs.Read(buffer, 0, buffer.Length);   
  17.     fs.Close();   
  18.     Stream ftpstream = ftp.GetRequestStream();   
  19.     ftpstream.Write(buffer, 0, buffer.Length);   
  20.     ftpstream.Close();   
  21. }  

Function can be used as
  1. ftpfile(@"/testfolder/testfile.xml", @"c:\testfile.xml");  

Reference :http://blog.logiclabz.com/c/ftp-file-upload-using-ftpwebrequest-in-net-c.aspx


Code to check Directory exists in ftp or not

private void btnCheck_Click(object sender, EventArgs e)
        {
            bool result = FtpDirectoryExists("ftp://micro123/First", "anonymous", "anonymous");
            MessageBox.Show("Folder"+result);
        }
        public bool FtpDirectoryExists(string directoryPath, string ftpUser, string ftpPassword)
        {
            bool IsExists = true;
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(directoryPath);
                request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
                request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                IsExists = false;
            }
            return IsExists;
        }
 

Sunday, May 20, 2012

 Ajax with Java script

Here is the link - http://sdrv.ms/DevCon2012-ClientSideScriptingControls
Access Viewstate from javascript in ASP.net

1)<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="..." />
var vCode = documents.forms[0]['__VIEWSTATE'].Value;
alert(dateView);

2)var viewState = document.getElementsByName('__VIEWSTATE');
or
var viewState = document.document.getElementById(('__VIEWSTATE')

3)This code explains how to access VIEWSTATE hidden field value from javascript which is in encrypted format. How do we decrypt it? var key_value = ‘<%=ViewState[“Key_Name”] %>’

Tuesday, February 28, 2012

Oracle related Issues

1:- In cmd check "echo %PATH%"  to get the environment variables with path .
2:-Start - Run - %windir%\SysWOW64\odbcad32.exe to get the providers registered with 32 bit.
3:-First time we r installing Oracle client need to configure tns names through NetConfigurationWizard.It will generate one tnsnames file in that specific location .IT contains the server name and all details.

Export to CSV

HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Buffer =
TrueHttpContext.Current.Response.AddHeader(
HttpContext.Current.Response.Charset =
"content-disposition", "attachment;filename=GLAmountsExport.csv")""HttpContext.Current.Response.ContentType = "application/text"
dt = GetXRefDataPageWise()
Dim dt As DataTable' GridView1.AllowPaging = False' GridView1.DataBind()

sb.Append(dt.Columns(k).ColumnName +
Dim sb As New StringBuilder()For k As Integer = 0 To dt.Columns.Count - 1","c)Nextsb.Append(vbCr & vbLf)


sb.Append(dt.Rows(i)(k).ToString +
For i As Integer = 0 To dt.Rows.Count - 1For k As Integer = 0 To dt.Columns.Count - 1","c)Nextsb.Append(vbCr & vbLf)
NextHttpContext.Current.Response.Output.Write(sb.ToString())
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()

Need to add  ","+c to display the values correctly in csv file .

Wednesday, February 8, 2012

IIS 7.0 Regarding issue in asp.Net Application

Junk data when convert binary to string

Here is the example :
Step 1: when I convert this string to binary I got the below output.
SELECT CONVERT(varbinary(max), '(DAYSBETWEENREADINGS(''SNOT'') * 100 / 365)')
Output:
0x28444159534245545745454E52454144494E47532827534E4F542729202A20313030202F2033363529

But in the table from which I am trying to convert binary to string I am having other than this, but sql server still returning the same string.

select CONVERT(varchar(max), 0x28444159534245545745454E52454144494E47532827534E4F542729202A20313030202F203336352900080030000000000000000000000000000000FFFF010000001C0001000000000000000000000000000000060007002A0000000000000000000000000000000100030000002B000200000000000000000000000000020000000000280001000000000000000000000000000100020000001A0000000000000000005940000000000100000000001B0001000000000000000000000000000100040005001A0000000000000000D076400000000001000000000002002800000000000000000000002B00140000000000000000001900444159534245545745454E52454144494E475300534E4F540000)
OutPut:
(DAYSBETWEENREADINGS('SNOT') * 100 / 365)


How to truncate the unnecessary sequence from binary data?


Solution :

For i = 0 To ds.Tables(t).Rows.Count - 1
                    dr = dt.NewRow()
                    For j As Integer = 0 To ds.Tables(t).Columns.Count - 2
                        If Not IsDBNull(ds.Tables(t).Rows(i)(j)) Then
                            If ds.Tables(t).Columns(j).DataType.Name = "Byte[]" Then

                                ss = "select convert(varchar(max),convert(varbinary(max),@byteArray)) as binarystr;"
                                cmd = New SqlCommand(ss.ToString, conn)
                                da1 = New SqlDataAdapter(cmd)
                                commonds = New DataSet
                                cmd.Parameters.Add("@byteArray", Data.SqlDbType.Image).Value = ds.Tables(t).Rows(i)(j)
                                da1.Fill(commonds)
                                If commonds.Tables(0).Rows.Count > 0 Then
                                    binarystr = commonds.Tables(0).Rows(0).Item(0)
                                    dr(j) = binarystr.Substring(0, binarystr.IndexOf(vbNullChar)) ‘We just done the substring, with the vbnullchar.

                                End If
                            Else
                                dr(j) = ds.Tables(t).Rows(i)(j)
                            End If
                        End If
                        commonds.Dispose()
                    Next
                    dt.Rows.Add(dr)
                Next
            Next
                     DataGridView1.DataSource = dt

IIS 6 Metabase and IIS 6 Configuration Compatibility

Getting this error when we are trying to open a .Net web application  in windows 7 .

 To access local IIS Web sites, we need to run Visual Studio in the context of an administrator account

  •     In Windows 7 or Vista , click Start, click All Programs, and then locate Visual Studio.
  •     Right-click Microsoft Visual Studio, and then click Run as administrator.





you need to install the "IIS Metabase and IIS6 Configuration Compatibility" feature under Internet Information Services-Web Management Tools-IIS 6 Management Capability to get the IIS6 ADSI provider installed.

  • First of all , you should have sufficient administrative access to turn or turn off windows features.

  • If you have the admin previliges , Please go to control panel in Windows and select Programs as shown in figure below.










  • In the settings page that opens, please select Turn windows features on or off .

  • Now go to Internet Information Services and then :
    • Expand Web Management Tools, expand IIS 6 Management Compatibility, and then select the IIS 6 Metabase and IIS 6 configuration compatibility check box.
    • Expand World Wide Web Services, expand Application Development Features, and then select the ASP.NET check box.
    • Expand World Wide Web Services, expand Security, and then select the Windows Authentication check box.
    • To enable Visual Studio to debug applications, you must configure IIS 7.0 with the Windows Authentication module. By default, the module is not configured as part of IIS.
    • Click OK to start the IIS and ASP.NET installation process.
    •  If you have resolved the above two, and still get the third error, Your project has been configured to work with IIS. Either you dont have IIS 6 metabase installed or your virtual directory is not configured as a application.

       This is something very smallish but this is something that IIS 7 + has brought in. Well in IIS 6 its just a virtual directory setup thats enough to run a application. But in IIS 7 , you have to make it as a application as well.
       Right click on your virtual directory and click on Convert to Application and you should get rid of this.


  • Wednesday, February 1, 2012

    Code to create & Write to a Text file

    Below code is to create and write text to a text file



     string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string fileLoc = mydocpath + @"\myEventLogSource_Pathwaytest.txt";
                StreamWriter sw;
                if (!File.Exists(fileLoc))
                {
                    sw = new StreamWriter(File.Open(fileLoc, FileMode.Create));               }
                else
                {
                    sw = new StreamWriter(File.Open(fileLoc, FileMode.Append));
                }  
    sw.Write("Hello");
    sw.Dispose();

    Friday, January 27, 2012

    SSRS Setup creation

    Refer :

    1:Download  RS Scripter Tool
    http://www.sqldbatips.com/showarticle.asp?ID=62
    2:http://weblogs.asp.net/akjoshi/archive/2009/01/29/using-rs-scripter-to-create-deployment-script-for-reporting-services.aspx


    Wednesday, January 18, 2012

    Best site for EBook downloads for .Net

    http://www.ebookee.biz/mcpd-70-519-exam-ref-designing-and-developing-web-applications-using-microsoft-net-framework-4.html#more-2242

    Elmah (Error Logging Modules and Handlers)

    Once we download a and register in our webapplication bin folder we can see our error log in Elmah.axd


    Refer:this below link for indepth detail

     http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

    SqlServer 2012(Denali) New Features

    http://www.sqlservergeeks.com/articles/sql-server-bi/80/new-built-in-functions-in-sql-server-2012-denali

     

    1:FORCESEEK hint is extended to specify columns used to seek in the specified index

    When SQL Server chooses seek over scan while retrieving record details, it will compare key value with search input, based on comparison result, Query engine will move to appropriate page. Suppose, index has multiple columns, if we don't want all key columns to consider, in SQL Server 2012, we can mention the index columns to consider when the index has multiple key columns. .

    SELECT CompanyID,CompanyName,Amount
    FROM COMPANIES
    WITH (FORCESEEK(Idx_Company(CompanyID)))
    WHERE CompanyID = 1
     

     2:FORCESCAN Hint added to force query optimizer to choose scan over seek

     

    Often while tuning stored procedures, we will see tables have the "seek" operator. Few times one of reason for slow performance is wrong estimates on number of rows. Because of that, there are more chances that query optimizer choose "SEEK" over "SCAN". To force optimizer to choose "SCAN" over "SEEK", FORCESCAN hint has been added.

    Select OH.OrderID,OD.ItemName,OH.OrderCost
    from OrderHeader OH
    INNER JOIN OrderDetails OD WITH (FORCESCAN)
    on OH.OrderID = OD.OrderID
     
     3:OVER Clause is enhanced to apply aggregate functions while applying "Order By"
     
    Before SQL Server 2012, We can't use "Order By" clause, while we are using aggregate functions in OVER clause. Suppose, to calculate company-wise cumulative revenues per year, we can't take the advantage of aggregate operators with OVER clause.
    Below syntax is invalid before SQL Server 2012.

    SUM(Amount) OVER (PARTITION BY CompanyID ORDER BY Year)
     
    4:PERCENT_RANK()
     
    PERCENT_RANK() function will returns the percentage value of rank of the element among its group.
    PERCENT_RANK() function value will be
    1. For first element in its group, it will be 0.
    2. For last element in its group, it will be 1.
    3. For remaining elements, it will be ( No. Of Elements Before that Element ) / (Total Elements - 1)

    .Net code for EXCEL

    .NET code for Excel Border setting 

     Excel.Border topBdr=range.Borders[Excel.XlBordersIndex.xlEdgeTop];
    Excel.Border bottomBdr=range.Borders[Excel.XlBordersIndex.xlEdgeBottom];
    Excel.Border leftBdr=range.Borders[Excel.XlBordersIndex.xlEdgeLeft];
    Excel.Border rightBdr=range.Borders[Excel.XlBordersIndex.xlEdgeRight];

    topBdr=Excel.XlLineStyle.xlContinuous;

    bottomBdr=Excel.XlLineStyle.xlContinuous;
    leftBdr=Excel.XlLineStyle.xlContinuous;
    rightBdr=Excel.XlLineStyle.xlContinuous;

     

    .NET code for Alignment in Excel 

    h1.HorizontalAlignment=Excel.XlHAlign.xlHAlignLeft;

    Java Script Debugger in Internet Explorer 8

    When Internet Explorer 8 is installed, built-in Java Script debugger ships along. Since this is an in-proc debugger one need not launch a separate app
    It has all the familiar Visual Studio 2008 Features debugger like call stacks, watches, locals and immediate window
    To get to the debugger just press SHIFT+F12, or click the developer tools icon in the command bar.
    After launching the Developer Tools, switch to the script tab
     

    Exampl to create autogenerated code verification

    Create a page with name “Captcha.aspx”


       1: IMG height="30" alt="" src=BuildCaptcha.aspx width="80">


       2: asp:TextBox runat="Server" ID="txtCaptcha">


       3: <asp:Button runat="Server" ID="btnSubmit" 


       4:            OnClick="btnSubmit_Click" 


       5:            Text="Submit" />


       6:  


       7: 3. On “btnSubmit_Click” place the following code


       8:  


       9: if (Page.IsValid && (txtCaptcha.Text.ToString() == 


      10:      Session["RandomStr"].ToString()))


      11: {


      12:   Response.Write("Code verification Successful");


      13: }


      14: else


      15: {


      16:   Response.Write( "Please enter info correctly");


      17: }
    Create one more page with BuildCaptcha.aspx
     
       1: Bitmap objBMP = new Bitmap(60, 20);


       2: Graphics objGraphics = Graphics.FromImage(objBMP);


       3: objGraphics.Clear(Color.Wheat);


       4: objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;


       5:  


       6:  


       7: //' Configure font to use for text


       8: Font objFont = new Font("Arial", 8, FontStyle.Italic);


       9: string randomStr = "";


      10: char[] myArray = new char[5];


      11: int x;


      12:  


      13: //That is to create the random # and add it to our string


      14: Random autoRand = new Random();


      15: for (x = 0; x < 5; x++)


      16: {


      17:   myArray[x] = System.Convert.ToChar(autoRand.Next(65,90));


      18:   randomStr += (myArray[x].ToString());


      19: }


      20:  


      21: //This is to add the string to session, to be compared later


      22: Session.Add("RandomStr", randomStr);


      23:  


      24: //' Write out the text


      25: objGraphics.DrawString(randomStr, objFont, Brushes.Red, 3, 3);


      26:  


      27: //' Set the content type and return the image


      28: Response.ContentType = "image/GIF";


      29: objBMP.Save(Response.OutputStream, ImageFormat.Gif);


      30: objFont.Dispose();


      31: objGraphics.Dispose();


      32: objBMP.Dispose();


      


     

    AssemblyKeyFile could not be found ERROR

    ERROR:
    1. The type or namespace name 'AssemblyKeyFileAttribute' could not be found (are you missing a using directive or an assembly reference?)

    2. The type or namespace name 'AssemblyKeyFile' could not be found (are you missing a using directive or an assembly reference?) 


    Just include "System.Reflection" namespace. It resolve above two errors.

    To associate an assembly with a strong key file to store it to GAC, we use should include following line after all the imports and before defing namespace.
    For VB.NET:  <Assembly: AssemblyKeyFile("c:\path\mykey.snk")>
    For C#:    [assembly: AssemblyKeyFile(@"c:\path\mykey.snk")]
     

    Tuesday, January 17, 2012

    How to block the ASP.NET page while ajax UpdateProgress is being displayed

    Write the css style :

    <style type="text/css">
          .hide
          {
              display: none;
          }
          .show
          {
              display: inherit;
          }
           .progressBackgroundFilter
          {
              position: absolute;
              top: 0px;
              bottom: 0px;
              left: 0px;
              right: 0px;
              overflow: hidden;
              padding: 0;
              margin: 0;
              background-color: #000;
              filter: alpha(opacity=50);
              opacity: 0.5;
              z-index: 1000;
          }
          .processMessage
          {
              position: absolute;
              font-family:Verdana;
              font-size:12px;
              font-weight:normal;
              color:#000066;
              top: 30%;
              left: 43%;
              padding: 10px;
              width: 18%;
              z-index: 1001;
              background-color: #fff;
          }
      </style>

    Design the Update progress as below :

    <asp:UpdateProgress ID="updPrgsBaselineTab" runat="server">
           <ProgressTemplate>
               <div id="progressBackgroundFilter" class="progressBackgroundFilter">
               </div>
               <div id="processMessage" class="processMessage">
                   <table width="100%">
                       <tr style="width: 100%">
                           <td style="width: 100%">
                               Please Wait..........
                           </td>
                       </tr>
                       <tr style="width: 100%">
                           <td style="width: 100%" align="center">
                               <img src="../Images/Update_Progress.gif" />
                           </td>
                       </tr>
                   </table>
               </div>
           </ProgressTemplate>
       </asp:UpdateProgress>

    Hibernate in XP & Code for Hibernate in Windows Application

    Below are the steps to enable Hibernate in Windows XP

    1. Right click on Desktop.
    2. Click on properties.
    3. Go to screen save tab.
    4. Click on power button
    5. Select Hibernate tab
    6. Check the checkbox “Enabled Hibernate”
    7. Apply the settings. 

    To provide this feature programatically in our .Net windows application



    using System.Windows.Forms;
    
    namespace CodeKicks.WinApp.Machine
    {
        public static class MyMachineHelper
        {
            public static void DoHibernate()
            {
                //Application.SetSuspendState(PowerState.Suspend, true, false);
                Application.SetSuspendState(PowerState.Hibernate, true, false);
            }
        }
    }

    Code for adding images to a imagelist from a folder



    Public Shared Function InitImageListFromDirectory(pDirectory As String) As ImageList
      Dim imageList As New ImageList()
    
      For Each f As String In System.IO.Directory.GetFiles(pDirectory)
        Try
          Dim img As Image = Image.FromFile(f)
          imageList.Images.Add(img)
            ' Out of Memory Exceptions are thrown in Image.FromFile if you pass in a non-image file.
        Catch
        End Try
      Next
    
      Return imageList
     End Function

    Monday, January 9, 2012

    Adding items to Listbox using threading


    In VB.Net windows application ,there is a issue adding items to listbox while there is a timer control .

    This issue can be resolved as below


     Private Delegate Sub UpdateListInvoker(ByVal StringList As List(Of String))

        Private Sub AddStatusLog(ByRef EventText As String)
            Dim i As Short

            If lstStatusLog.Items.Count > 30000 Then
                For i = 1 To 1000
                    lstStatusLog.Items.RemoveAt(0)
                Next i
            End If

            Dim strval As String = VB6.Format(Now, "long time") & " " & EventText
            Dim nThread As New Threading.Thread(AddressOf TestList)

            nThread.Start(strval)

                   sta.Items.Item(1).Text = EventText
        End Sub

        Private Sub TestList(ByVal EventText As Object)
            UpdateList(New List(Of String)(New String() {EventText}))
        End Sub

        Private Sub UpdateList(ByVal strList As List(Of String))
            If Me.lstStatusLog.InvokeRequired Then
                Me.lstStatusLog.Invoke(New UpdateListInvoker(AddressOf UpdateList), strList)
            Else
                Me.lstStatusLog.Items.AddRange(strList.ToArray)
            End If
        End Sub

    Knowing u r sqlserver is 32 bit or 64 bit

      SELECT @@VERSION
    If the version returned is x86 that means it is a 32 bit installation and if it is x64 then it means it is a 64 bit installation.