I am using the below code in c# page. It's working fine. I am new for vb.net. I convert the same using online converter but i got error i can't understood that error. Please help me to do the same.
string StrInputParam = "TYPE:5#MOBILE:" + Mobile + "#PASS:" + Password + "";
string StrSPName = ConfigurationManager.AppSettings["SP_RED_USER_DETAILS"];
string[] ArrayVal = StrInputParam.Split('#');
StrSPName = Regex.Replace(StrSPName, #"\[(.+?)\]", m =>
{
string StrParamName = m.Groups[1].Value;
string StrParamValue = ArrayVal.Select(s => s.Split(new[] { ':' }, 2))
.Where(p => p.Length == 2)
.Where(p => p[0] == StrParamName)
.Select(p => p[1])
.FirstOrDefault();
return StrParamValue ?? "0"; // "0" instead of m.Value
});
Error:
Overload resolution failed because no accessible 'Replace' can be called with these arguments:
'Public Function Replace(input As String, evaluator As System.Text.RegularExpressions.MatchEvaluator, count As Integer) As String': Value of type 'String' cannot be converted to 'System.Text.RegularExpressions.MatchEvaluator'.
'Public Function Replace(input As String, evaluator As System.Text.RegularExpressions.MatchEvaluator, count As Integer) As String': Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.......
You can use below code :-
Dim StrInputParam As String = "TYPE:5#MOBILE:" & Mobile & "#PASS:" & Password & ""
Dim StrSPName As String = ConfigurationManager.AppSettings("SP_RED_USER_DETAILS")
Dim ArrayVal As String() = StrInputParam.Split("#"C)
StrSPName = Regex.Replace(StrSPName, "\[(.+?)\]", Function(m)
Dim StrParamName As String = m.Groups(1).Value
Dim StrParamValue As String = ArrayVal.[Select](Function(s) s.Split(New () {":"C}, 2)).Where(Function(p) p.Length = 2).Where(Function(p) p(0) = StrParamName).[Select](Function(p) p(1)).FirstOrDefault()
' "0" instead of m.Value
Return If(StrParamValue, "0")
End Function)
Use below code
Dim StrInputParam As String = "TYPE:5#MOBILE:" + Mobile + "#PASS:" + Password + ""
Dim StrSPName As String = ConfigurationManager.AppSettings("SP_RED_USER_DETAILS")
Dim ArrayVal As String() = StrInputParam.Split("#"C)
StrSPName = Regex.Replace(StrSPName, "\[(.+?)\]", Function(m)
Dim StrParamName As String = m.Groups(1).Value
Dim StrParamValue As String = ArrayVal.Select(Function(s) s.Split(New () {":"C}, 2))
.Where(Function(p) p.Length = 2)
.Where(Function(p) p(0) = StrParamName)
.Select(Function(p) (1))
.FirstOrDefault()
Return If(StrParamValue, "0")
End Function)
Or try this code
Dim StrInputParam As String = "TYPE:5#MOBILE:" + Mobile + "#PASS:" + Password + ""
Dim StrSPName As String = ConfigurationManager.AppSettings("SP_RED_USER_DETAILS")
Dim ArrayVal() As String = StrInputParam.Split("#"c)
StrSPName = Regex.Replace(StrSPName, "\[(.+?)\]", m =>
{
Dim StrParamName As String = m.Groups(1).Value
Dim StrParamValue As String = ArrayVal.Select(s = > s.Split(New()
{
":"c
}
, 2))
.Where(p => p.Length = 2)
.Where(p => p(0) = StrParamName)
.Select(p => p(1))
.FirstOrDefault()
Return StrParamValue ?? "0"
}
)
There you go, I converted it for you:
Dim StrInputParam As String = "TYPE:5#MOBILE:" & Mobile & "#PASS:" & Password & ""
Dim StrSPName As String = ConfigurationManager.AppSettings("SP_RED_USER_DETAILS")
Dim ArrayVal() As String = StrInputParam.Split("#"c)
StrSPName = Regex.Replace(StrSPName, "\[(.+?)\]", Function(m) ' "0" instead of m.Value
Dim StrParamName As String = m.Groups(1).Value
Dim StrParamValue As String = ArrayVal.Select(Function(s) s.Split( { ":"c }, 2)).Where(Function(p) p.Length = 2).Where(Function(p) p(0) = StrParamName).Select(Function(p) p(1)).FirstOrDefault()
Return If(StrParamValue, "0")
End Function)
Related
hi firends i have started with sap b1 i created my own add-on sap using c# in visual studio 2010 my form will sent a value to my crystal report directly without showing previou any one can help my version sap is 9.2
i tried this code but it doesn't work
//add crystalreport to my add-on
SAPbobsCOM.ReportTypesService rptTypeService = (SAPbobsCOM.ReportTypesService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService);
SAPbobsCOM.ReportType newType = (SAPbobsCOM.ReportType)
rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType);
newType.TypeName = "CodeBarre_etat";
newType.AddonName = "PRINT_CODEBARRE";
newType.AddonFormType = "PRINT_CODEBARRE";
newType.MenuID = "PRINT_CODEBARRE";
SAPbobsCOM.ReportTypeParams newTypeParam = rptTypeService.AddReportType(newType);
//add layout to my report
SAPbobsCOM.ReportLayoutsService rptService = (SAPbobsCOM.ReportLayoutsService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService);
SAPbobsCOM.ReportLayout newReport = (SAPbobsCOM.ReportLayout)
rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout);
newReport.Author = Menu.company.UserName;
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal;
newReport.Name = "PRINT_CODEBARREL";
newReport.TypeCode = newTypeParam.TypeCode;
SAPbobsCOM.ReportLayoutParams newReportParam = rptService.AddReportLayout(newReport);
// Set the report layout into the report type.
newType = rptTypeService.GetReportType(newTypeParam);
newType.DefaultReportLayout = newReportParam.LayoutCode;
rptTypeService.UpdateReportType(newType);
SAPbobsCOM.BlobParams oBlobParams = (SAPbobsCOM.BlobParams)
Menu. company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams);
oBlobParams.Table = "OITM";
oBlobParams.Field = "Template";
SAPbobsCOM.BlobTableKeySegment oKeySegment = oBlobParams.BlobTableKeySegments.Add();
oKeySegment.Name = "ItemCode";
oKeySegment.Value = newReportParam.LayoutCode;
FileStream oFile = new FileStream("CodeBarre_etat.rpt", System.IO.FileMode.Open);
int fileSize = (int)oFile.Length;
byte[] buf = new byte[fileSize];
oFile.Read(buf, 0, fileSize);
oFile.Dispose();
//SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)
//Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob);
SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)(Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob));
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize);
Menu.company.GetCompanyService().SetBlob(oBlobParams, oBlob);
Not sure what the issue might be with your code, but below is a working implementation of what you're trying to do (albeit in VB, not in C#, but translating it should be fairly trivial).
Here's a sample call:
setCrystalReport(REPORT_TITLE_SUMMARY, My.Settings.ReportsPath.TrimEnd("\") & "\" & "comm_report_summary.rpt", _
oForm, "myFormTypeID", "My Add-On Name", "MENU_ID_VALUE")
Function:
'Returns new CR TypeCode
Private Function setCrystalReport(ByVal rptName As String, ByVal rptPath As String, ByRef oForm As SAPbouiCOM.Form, ByVal formType As String, _
ByVal addOnName As String, ByVal menuID As String) As String
Try
'1. Ad a new report type => ReportTypesService (8.81+ only)
Dim rptTypeService As SAPbobsCOM.ReportTypesService
Dim newType As SAPbobsCOM.ReportType
rptTypeService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService)
newType = rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType)
newType.TypeName = rptName
newType.AddonName = addOnName
newType.AddonFormType = formType
newType.MenuID = menuID
Dim newTypeParam As SAPbobsCOM.ReportTypeParams
newTypeParam = rptTypeService.AddReportType(newType)
'2. Add a new report layout => ReportLayoutService
Dim rptService As SAPbobsCOM.ReportLayoutsService
Dim newReport As SAPbobsCOM.ReportLayout
rptService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService)
newReport = rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout)
newReport.Author = SBO_Company.UserName
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal
newReport.Name = rptName
newReport.TypeCode = newTypeParam.TypeCode
Dim newReportParam As SAPbobsCOM.ReportLayoutParams
newReportParam = rptService.AddReportLayout(newReport)
'3. Set the report layout into the report type
newType = rptTypeService.GetReportType(newTypeParam)
newType.DefaultReportLayout = newReportParam.LayoutCode
rptTypeService.UpdateReportType(newType)
'4. Link the Report layout code to the Crystal Report file
Dim oBlobParams As SAPbobsCOM.BlobParams
Dim oKeySegment As SAPbobsCOM.BlobTableKeySegment
oBlobParams = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams)
oBlobParams.Table = "RDOC"
oBlobParams.Field = "Template"
oKeySegment = oBlobParams.BlobTableKeySegments.Add()
oKeySegment.Name = "DocCode"
oKeySegment.Value = newReportParam.LayoutCode
Dim oFile As New FileStream(rptPath, System.IO.FileMode.Open)
Dim fileSize As Integer
fileSize = oFile.Length
Dim buf(fileSize) As Byte
oFile.Read(buf, 0, fileSize)
oFile.Dispose()
Dim oBlob As SAPbobsCOM.Blob
oBlob = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob)
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize)
SBO_Company.GetCompanyService().SetBlob(oBlobParams, oBlob)
'5. Link the new report type to your form
Return newType.TypeCode
Catch ex As Exception
Dim exString As String = ""
exString = "Exception caught in setCrystalReport Method. Details: " & ex.Message
If Not ex.InnerException Is Nothing Then
exString += " Inner Exception: " + ex.InnerException.Message
End If
SBO_Application.StatusBar.SetText(exString, SAPbouiCOM.BoMessageTime.bmt_Medium, _
SAPbouiCOM.BoStatusBarMessageType.smt_Error)
Return "-1"
End Try
End Function
This question already has answers here:
Vb.Net convert StrDup to C#.net
(3 answers)
Closed 7 years ago.
Hello I have a code that use with VB.net:
Public Shared Function GetNextID(ByVal Prefix As String) As String
Dim dt As DataTable = Database.GetDataTable("select * from _NumberGeneration Where Entity = '" & Prefix & "'")
If dt Is Nothing OrElse dt.Rows.Count = 0 Then Return ""
Dim format As String = dt.Rows(0)("Format") & ""
Dim sqlCnt As String = dt.Rows(0)("SQL") & ""
Dim cnt As Int32 = Val(Database.ExecuteScalar(sqlCnt)) + 1 ' 11
Dim RN As String = format.Substring(format.IndexOf("["c), 4) ' [R5]
Dim newRN As String = StrDup(CInt(RN.Substring(2,1), "0"c) ' 00000
newRN = cnt.ToString(newRN) ' String.Format(newRN, cnt) ' 00011
Dim newformat As String = format.Replace(RN, newRN) '"PR"yyMM00011
Return Today.ToString(newformat) ' String.Format(newformat, cnt)
End Function
For the StrDup When I write the code with C# same as code below:
string newRN = new string (int.Parse(RN.Substring(2, 1)),'0');
It show the error.
Use the string constructor with character and count parameters:
string newRN = new string('0', 4);
You could also reference the Microsoft.VisualBasic assembly and call the method via the Strings module, but the alternative above is pretty simple.
I need to verify that a provided username is a Domain Administrator in c#.
Any idea's on how to do this?
You can use WindowsIdentity to get the current user.
Then create a WindowsPrincipal with the WindowsIdentity.
And check WindowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator)
Hope this can help you.
EDIT : I just see the ASP tag now... This link could help you, same thing but for ASP.
Function ADUserInfo(sLogonUser, cOption)
Dim oConnection
Dim oCommand
Dim oRoot
Dim oDomain
Dim sADsPath
Dim sDomain
sDomain = Mid(sLogonUser, 1, Instr(1, sLogonUser, "\") - 1)
Set oConnection = CreateObject("ADODB.Connection")
With oConnection
.Provider = "ADsDSOObject"
.Mode = "1" 'Read
.Properties("Encrypt Password") = True
.Open "Active Directory Provider"
End With
Set oCommand = CreateObject("ADODB.Command")
oCommand.ActiveConnection = oConnection
Set oRoot = GetObject("LDAP://" & sDomain & "/rootdse")
Set oDomain = GetObject("LDAP://" & sDomain & "/" & oRoot.Get("defaultNamingContext"))
sADsPath = "<" & oDomain.ADsPath & ">"
Select Case lcase(cOption)
Case "groups"
ADUserInfo = ADUserGroups(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Case "name"
ADUserInfo = ADUserName(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Case "supervisor"
End Select
End Function
Function ADUserGroups(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Dim sFilter
Dim sAttribsToReturn
Dim sDepth
Dim sDomainSID
Dim vObjectSID
Dim sObjectSID
Dim sGroupRID
Dim iPrimaryGroupID
Dim oPrimaryGroup
Dim oRS
Dim value
Dim cGroups
Dim sDomain
Dim sLogonName
sDomain = Mid(sLogonUser, 1, Instr(1, sLogonUser, "\") - 1)
sLogonName = Mid(sLogonUser, Instr(1, sLogonUser, "\") + 1)
sFilter = "(&(objectCategory=Person)(objectClass=user)(sAMAccountName=" & sLogonName & "))"
sAttribsToReturn = "memberOf,primaryGroupID,objectSID"
sDepth = "subTree"
ocommand.CommandText = sADsPath & ";" & sFilter & ";" & sAttribsToReturn & ";" & sDepth
Set oRS = ocommand.Execute
' Only one user should meet the criteria
If (oRS.RecordCount = 1) Then
' Get that user's info
For i = 0 To oRS.Fields.Count - 1
If (oRS.Fields(i).Name = "memberOf") Then
' I've never seen this field come back with more than
' ONE value, but the original code I started with
' treated the memberOf property as though it was a
' collection. So, I've left it a collection until
' I can verify it. KLW
cGroups = ""
For Each value In oRS.Fields(i).Value
cGroups = cGroups & replace(split(value,",")(0),"CN=","") & ";"
Next
ElseIf (oRS.Fields(i).Name = "primaryGroupID") Then
' need this to get the PrimaryGroup after other group membership has been obtained
' (Primary Group ID and Object SID ID needed to get the primary group)
iPrimaryGroupID = oRS.Fields(i).Value
ElseIf (oRS.Fields(i).Name = "objectSID") Then
' adVarBinary -- need this to get the PrimaryGroup.
' It is not included in the memberOf group list
vObjectSID = oRS.Fields(i).Value
sObjectSID = SDDL_SID(vObjectSID)
End If
Next
' The primary group is not included in memberOf...
' We have the SDDL form of the user's SID.
' Remove the user's RID ( the last sub authority)
' up to the "-"
'
sDomainSID = Mid(sObjectSID, 1, (InStrREV(sObjectSID,"-")))
' Build the SID of the Primary group
' from the domainSID and the Primary Group RID in
' the PrimaryGroupID.
'
sGroupRID = StrRID(iPrimaryGroupID)
sDomainSID = sDomainSID & sGroupRID
' Get the primary group
'
set oPrimaryGroup = GetObject("LDAP://" & sDomain & "/<SID=" & sDomainSID & ">")
cGroups = replace(split(oPrimaryGroup.Get("DistinguishedName"),",")(0),"CN=","") & ";" & cGroups
ADUserGroups = cGroups
End If
End Function
Function ADUserName(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Dim sFilter
Dim sAttribsToReturn
Dim sDepth
Dim sDomainSID
Dim vObjectSID
Dim sObjectSID
Dim sGroupRID
Dim iPrimaryGroupID
Dim oPrimaryGroup
Dim oRS
Dim value
Dim sDomain
Dim sLogonName
sDomain = Mid(sLogonUser, 1, Instr(1, sLogonUser, "\") - 1)
sLogonName = Mid(sLogonUser, Instr(1, sLogonUser, "\") + 1)
sFilter = "(&(objectCategory=Person)(objectClass=user)(sAMAccountName=" & sLogonName & "))"
sAttribsToReturn = "distinguishedName"
sDepth = "subTree"
ocommand.CommandText = sADsPath & ";" & sFilter & ";" & sAttribsToReturn & ";" & sDepth
Set oRS = ocommand.Execute
' Only one user should meet the criteria
If (oRS.RecordCount = 1) Then
' Get that user's info
For i = 0 To oRS.Fields.Count - 1
If (oRS.Fields(i).Name = "distinguishedName") Then
ADUserName = replace(split(oRS.Fields(i).Value,",")(0),"CN=","")
End If
Next
End If
End Function
function SDDL_SID ( oSID )
dim IssueAuthorities(11)
Dim SubAuthorities
Dim strSDDL
Dim IssueIndex
Dim Revision
Dim i, j, k, index, p2, subtotal, dblSubAuth
IssueAuthorities(0) = "-0-0"
IssueAuthorities(1) = "-1-0"
IssueAuthorities(2) = "-2-0"
IssueAuthorities(3) = "-3-0"
IssueAuthorities(4) = "-4"
IssueAuthorities(5) = "-5"
IssueAuthorities(6) = "-?"
IssueAuthorities(7) = "-?"
IssueAuthorities(8) = "-?"
IssueAuthorities(9) = "-?"
' First byte is the revision value
'
Revision = ascb(midB(osid,1,1))
' Second byte is the number of sub authorities in the
' SID
'
SubAuthorities = CInt(ascb(midb(oSID,2,1)))
strSDDL = "S-" & Revision
IssueIndex = CInt(ascb(midb(oSID,8,1)))
strSDDL = strSDDL & IssueAuthorities(IssueIndex)
index = 9
i = index
for k = 1 to SubAuthorities
p2 = 0
subtotal = 0
for j = 1 to 4
dblSubAuth = CDbl(ascb(midb(osid,i,1))) * (2^p2)
subTotal = subTotal + dblSubAuth
p2 = p2 + 8
i = i + 1
next
' Convert the value to a string, add it to the SDDL Sid and continue
'
strSDDL = strSDDL & "-" & cstr(subTotal)
next
SDDL_SID = strSDDL
end function
function Get_HexString( oSID )
Dim outStr, i, b
outStr = ""
for i = 0 to Ubound(oSid)
b = hex(ascb(midb(oSid,i+1,1)))
if( len(b) = 1 ) then b = "0" & b
outStr = outStr & b
next
Get_HexString = outStr
end function
function StrRID( inVal )
dim dLocal
if( (inVal and &H80000000) <> 0 ) then
dLocal = CDbl((inval and &H7FFFFFFF))
dLocal = dLocal + 2^31
StrRID = cstr(dLocal)
else
StrRID = Cstr(inVal)
end if
end function
I have an excel template file saved in web server folder.
During the run time I am giving the data source using the variable(dunsno) and date
but it throws an error:
Format of the initialization string does not conform to specification starting at index 3.
I just want to know how to write the connection string in the server side
I have done this:
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='Server.MapPath(~/Profile/ + "Tempfile" + dunsno + DateTime.Today.ToString("dd.MM.yyyy") + ".xls");Extended Properties=Excel 8.0;";
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("~/temp/"));
var fileList = directoryInfo.GetFiles();
string newFileName = Server.MapPath("~/Profile/" + "Tempfile" + dunsno + DateTime.Today.ToString("dd.MM.yyyy") + ".xls");
foreach (FileInfo fleInfo in fileList)
{
fleInfo.CopyTo(newFileName, true);
}
OleDbConnection MyConnection;
OleDbCommand MyCommand = new OleDbCommand();
MyConnection = new OleDbConnection(connStr);
MyConnection.Open();
MyCommand.Connection = MyConnection;
string sql = "Insert into [Sheet1$] (id,name) values('3','c')";
MyCommand.CommandText = sql;
MyCommand.ExecuteNonQuery();
MyConnection.Close();
}
Some more VBA point to have this clarity :
Sub GrabLastNames()
'dimension (set aside memory for) our variables
Dim objIE As InternetExplorer
Dim ele As HTMLLinkElement
Dim e As HTMLLinkElement
Dim h As HTMLLinkElement
Dim t As HTMLTable
Dim s As String
Dim x, y, z
Dim c As Integer
Dim post As Object, Elem As Object
Set objIE = New InternetExplorer
objIE.Visible = True
i = 0
objIE.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=ALB&commit=OK"
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
Set post = objIE.Document.getElementById("countrycriteria_country")
For Each Elem In post.getElementsByTagName("option")
c = c + 1
If c = 6 Then Exit For
Elem.Selected = True
objIE.Document.getElementById("countrycriteria_country").Focus
objIE.Document.getElementById("countrycriteria_country").FireEvent ("onchange")
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
For Each ele In objIE.Document.getElementsByTagName("table") '.getElementById("myTable").getElementsByTagName("tr")
s = LCase(Trim(ele.innerText))
If InStr(s, "immunization schedule") Or InStr(s, "percentage target population vaccinated by antigen") Then
For Each e In ele.Rows
i = i + 1
j = 3
' Sheet1.Cells(i, 1).Value = Elem.Value
For Each h In e.Cells
j = j + 1
Sheet1.Cells(i, j).Value = h.innerText
Next h
Next e
End If
Next ele
Next Elem
ActiveWorkbook.Save
End Sub
Sub Select_Item()
Dim post As Object, Elem As Object
With CreateObject("InternetExplorer.Application")
.Visible = True
.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=ALB&commit=OK" ''stored the html elements within "element.html" file to test it locally
While .Busy = True Or .ReadyState < 4: DoEvents: Wend
Set post = .Document.getElementById("countrycriteria_country")
For Each Elem In post.getElementsByTagName("option")
If Elem.Value = "BHS" Then Elem.Selected = True: Exit For
' i = i + 1
' If i = 4 Then Exit For
Next Elem
Application.Wait (Now + TimeValue("0:00:02"))
.Document.getElementById("countrycriteria_country").Focus
Application.Wait (Now + TimeValue("0:00:02"))
'.Document.getElementById("countrycriteria_country").Change
.Document.getElementById("countrycriteria_country").FireEvent ("onchange")
End With
End Sub
' Loop vba========
' Elem.Selected = True
' objIE.Document.getElementById("countrycriteria_country").Focus
' objIE.Document.getElementById("countrycriteria_country").FireEvent ("onchange")
' Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
Sub getCoverage()
Application.ScreenUpdating = False
Sheet1.Cells.Clear
'dimension (set aside memory for) our variables
Dim objIE As InternetExplorer
Dim ele As HTMLLinkElement
Dim e As HTMLLinkElement
Dim h As HTMLLinkElement
Dim t As HTMLTable
Dim s As String
Dim x, y, z
Dim con(1000)
Dim c As Integer
Dim post As Object, Elem As Object
Dim s1 As String, s2 As String, s3 As String, s4 As String
Set objIE = New InternetExplorer
objIE.Visible = True
' Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
s1 = LCase(shtweb.Range("d5").Value)
s2 = LCase(shtweb.Range("e5").Value)
s3 = LCase(shtweb.Range("f5").Value)
s4 = LCase(shtweb.Range("g5").Value)
s2 = IIf(s2 = "", "fsdfswew", s2)
s3 = IIf(s3 = "", "fsdfswew", s3)
s4 = IIf(s4 = "", "fsdfswew", s4)
i = 0
objIE.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=ALB&commit=OK"
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
Set post = objIE.Document.getElementById("countrycriteria_country")
For Each Elem In post.getElementsByTagName("option")
con(c) = Elem.Value
c = c + 1
Next Elem
'objIE.
For k = 0 To c
If con(k) = "" Then Exit For
objIE.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=" & con(k) & "&commit=OK"
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
For Each ele In objIE.Document.getElementsByTagName("table") '.getElementById("myTable").getElementsByTagName("tr")
s = LCase(Trim(ele.innerText))
If InStr(s, s1) Or InStr(s, s2) Or InStr(s, s3) Or InStr(s, s4) Then
For Each e In ele.Rows
i = i + 1
j = 3
Sheet1.Cells(i, 1).Value = con(k)
For Each h In e.Cells
j = j + 1
If Left(h.innerText, 1) = "=" Then
Sheet1.Cells(i, j).Value = "'" & h.innerText
Else
Sheet1.Cells(i, j).Value = h.innerText
End If
Next h
Next e
End If
Next ele
Next k
ActiveWorkbook.Save
Application.ScreenUpdating = True
End Sub
use Path.Combine and a OleDbConnectionStringBuilder to create a valid connection-string:
var conString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}"
, Path.Combine(dir, "nik.mdb"));
var conBuilder = new OleDbConnectionStringBuilder(conString);
using (var con = new OleDbConnection(conBuilder.ConnectionString))
{
// ...
}
Maybe you have white-spaces in the connection string.
I have a WEB API C#, inside it I have Data which is a link, for example: images/Chinese/AbaloneEggCustard.jpg
but in JSON, it appear like this:
[{"BackgroundImage":"images\/Chinese\/AbaloneEggCustard.jpg", ......}]
May I know how can I remove the slash? Need it remove so hopefully I can access the images when I link with azure.
Here's my controller codes:
public IEnumerable<Food> Get()
{
List<Food> Cases = new List<Food>();
try
{
string connectionString = ConfigurationManager.ConnectionStrings["HealthyFoodDBConnectionString"].ConnectionString;
myConnection = new SqlConnection(connectionString);
myConnection.Open();
string sql = "SELECT * from [Recipe] ";
myCommand = new SqlCommand(sql, myConnection);
myDataReader = myCommand.ExecuteReader();
while (myDataReader.Read())
{
Cases.Add(new Food()
{
RecipeID = (int)myDataReader["RecipeID"],
RecipeTitle = (string)myDataReader["RecipeTitle"],
FoodCategoryID = Convert.ToInt32(myDataReader["FoodCategoryId"]),
Serves = (string)myDataReader["Serves"],
PerServing = (string)myDataReader["PerServing"],
Favourite = ((Convert.ToInt32(myDataReader["Favourite"]) == 1) ? true : false),
Directions = (string)myDataReader["Directions"],
BackgroundImage = (string)myDataReader["BackgroundImage"],
HealthyTips = (string)myDataReader["HealthyTips"],
Nutritions = (string)myDataReader["Nutritions"],
Ingredients = (string)myDataReader["Ingredients"]
});
}
}
finally
{
if (myConnection != null)
myConnection.Close();
}
return Cases;
}
here's my Index.cshtml code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
// Send an AJAX request
$.getJSON("api/food/",
function (data) {
// on success, 'data' contains a list of products
$.each(data, function (key, val){
//format the text to display
var str = val.RecipeTitle + ' | ' + val.FoodCategoryID + ' | ' + val.Serves + ' | ' + val.PerServing + ' | ' + val.Favourites + ' | ' + val.Directions + ' | ' + val.BackgroundImage + ' | ' + val.HealthyTips + ' | ' + val.Nutritions + ' | ' + val.Ingredients;
// add a list item for the product
$('<li/>', { html: str }).appendTo($('#cases'));
});
});
});
Assuming you're calling the API, and getting back the normally escaped JSON object:
var myObject = Foo.API.Call(); //returns object with BackgroundImage property.
If you're saving the result to a text file, you can use JavaScriptSerializer:
var bg = new JavaScriptSerializer().Deserialize(myObject);
using (var writer = new StreamWriter(#"C:\foo.txt"))
{
writer.Write(bg.BackgroundImage);
}
The text file saved should be the unescaped string.
You can use this:
string deserializedString = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(serializedString);